Home > front end >  How to make objects look in the direction of travel?
How to make objects look in the direction of travel?

Time:10-07

I'm making my own copy of a game I saw but when I try to get the rockets to face the direction they are travelling in it just doesn't work consistently.

public class FriendlyRocket : MonoBehaviour
{
    public Rigidbody2D self;
    private Vector2 mousePos;
    public Transform mouse;
    //public float timer;
    // Start is called before the first frame update
    void Start()
    {
        mouse = GameObject.Find("Mouse").transform;
        mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        //mousePos.z  = 10;
        //mousePos = Input.mousePosition;
        transform.LookAt(mouse.transform);
        //transform.eulerAngles.z = 0;
        if (mousePos.x < 0) { transform.eulerAngles = new Vector3(0f, 0f, transform.eulerAngles.x   90); }
        if (mousePos.x > 0) { transform.eulerAngles = new Vector3(0f, 0f, transform.eulerAngles.x   270); }

        //self = GetComponent<Rigidbody2D>();
        //self.velocity = new Vector2(self.velocity.x, 10f);
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = Vector2.MoveTowards(transform.position, mousePos, 10f * Time.deltaTime);
        /*if (timer < 0)
        {
            timer -= Time.deltaTime;
        }
        if(timer>0)
        {
            Destroy(gameObject);
        }*/
    }
}

Any thoughts?

CodePudding user response:

It is hard to answer the question without visual representation. But I believe the issue is associated with the fact that you set mousePos only on start but moving in mousePos direction each frame. So if mousePos cannot be changed than it is ok but is mousePos is changing during the time than you should also update the value of mousePos. And of course LookAt() should also be called each frame to update rotation if the direction is changed. I hope these ideas will help you.

CodePudding user response:

I did not fully understand the question but you must update your mousePos in void update() For the object to follow the mouse

    void Update()
{
    transform.position = Vector2.MoveTowards(transform.position, mousePos, 
    10f * Time.deltaTime);
    mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
  • Related