简体   繁体   中英

Why this code moving my gameobject in such an odd way?

My Code

        Vector2 moveDirection;
        moveDirection = (Sensitive.transform.position - gameObject.transform.position).normalized;
        float deg = Mathf.Rad2Deg * Mathf.Atan(moveDirection.x / -moveDirection.y);
        if (moveDirection.y < 0) deg -= 180;
        Vector3 to = new Vector3(0, 0, deg);
        transform.eulerAngles = to;
        transform.Translate(new Vector3(moveDirection.x, moveDirection.y) * speed * Time.deltaTime);

In the update function intended to look at and move to Sensitive, though it points correctly doesn't move correctly and I can figure out why.

transform.Translate by default interprets the input as a local direction & distance. You're providing the input in world direction & distance, so you should use the optional 2nd parameter and specify Space.World :

transform.Translate(new Vector3(moveDirection.x, moveDirection.y) 
    * (speed * Time.deltaTime), Space.World);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM