Make an object move towards another objects position

前端 未结 2 730
情深已故
情深已故 2021-01-22 01:23

What I have currently is two objects that can be played though nav keys and the other one with wasd. The point is to get the 3rd object and score a point, and it randoms a new p

2条回答
  •  [愿得一人]
    2021-01-22 02:03

    The easiest and most accurate way, is to rely on vector geometry.

    Define class

    public class Vector2 {
    
         public float x {get;set;}; 
         public float y {get;set;}; 
    
         public Vector2(float a_x, float a_y, float b_x, float b_y)
         {
            x = b_x - a_x;
            y = b_y - a_y;
         }
    
         //calculate vector length
         public float Length {
              get {
                   return Math.Sqrt((x * x) + (y * y));
              }
         }
    
         public void SetVectorLength(float desiredLength){
                double r = desiredLength/ this.Length;
                this.x *= r;
                this.y *= r;
         }
    
    }
    

    this is just a set of functions for this case, but you can add others, plenty of them need for various parts of your calculations.

    After what you have to do is just, calculate next position of your vertex toward the directional vector.

    //hypothetical X coordinate
    float x_coord = 1.34f; 
    
    //move towards the vector 
    var vector = new Vector2(10, 10, 20, 20);
    
    //set vector move step 
    vector.SetLength(0.1f);
    
    var movedX = x_coord + vector.x;
    

    Repeat: this is just hypothetical example, you need to work on this. It's hard to put in small answer all related vector geometry stuff.

提交回复
热议问题