简体   繁体   中英

How do I make a 2D object face the direction it is moving like drifting

在此处输入图片说明

As shown in the picture above, I have two GameObject s: the car and the circle. The car follows the circle, and the circle is moving with the cursor. Currently, my car is following the circle from a distance. When the circle moves along the x-axis, I want to rotate the car like it's drifting.

Here is my car follow script:

public class Follow : MonoBehaviour
{

    public Transform leader;
    public float followSharpness = 0.1f;

    Vector3 _followOffset;

    void Start()
    {
        // Cache the initial offset at time of load/spawn:
        _followOffset = transform.position - leader.position;
    }

    void LateUpdate()
    {
        // Apply that offset to get a target position.
        Vector3 targetPosition = leader.position + _followOffset;
        //GetComponent<Rigidbody2D>().rotation = 1.5f;

        // Keep our y position unchanged.
        //targetPosition.y = transform.position.y;

        // Smooth follow.    
        transform.position += (targetPosition - transform.position) * followSharpness;

    }
}

You could try to use Transform.LookAt :

void LateUpdate()
{
    Vector3 targetPosition = leader.position + _followOffset;
    transform.position += (targetPosition - transform.position) * followSharpness;
    transform.LookAt(leader);
}

Disclaimer: I'm not able to test that this code works right now, you'll have to try it out and see if it produces the desired result.

So from what you described, is you want to make the car always facing the cursor, so it is always "looking at" the cursor, here is how you can do it:

  Vector3 diff = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
     diff.Normalize();

     float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
     transform.rotation = Quaternion.Euler(0f, 0f, rot_z - 90);

From Answer: LookAt 2D Equivalent ?

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