简体   繁体   中英

Unity 2D Sprite rotate toward object

I am making this game in unity. It is a 2d race car game where the player is a racer and has to navigate through the road avoiding crashing into cones or other other cars that are also driving on the road. I've created a path for the other NPC cars that are driving on the road and that part works. Those cars follow the path the way I want them to. But what I want to do now is make the NPC car sprites rotate towards the next path point.

So for example if the vehicle is switching lanes or turning a corner, the car should rotate and point towards the next point in their path. This is the code I have:

public Transform[] waypoints;   //array to hold all the waypoints in the sprite's path

    [SerializeField]
    public float moveSpeed = 2.0f;

    public int wayPointIndex = 0;

    // Start is called before the first frame update
    void Start()
    {
        transform.position = waypoints[wayPointIndex].transform.position;
    }

    // Update is called once per frame
    void Update()
    {
        Move();
    }

    public void Move(){
        if(wayPointIndex <= waypoints.Length - 1){
            transform.position = Vector3.MoveTowards(transform.position, waypoints[wayPointIndex].transform.position, moveSpeed * Time.deltaTime);

            if(transform.position == waypoints[wayPointIndex].transform.position){
                wayPointIndex+=1;
            }
        }
    }

This is a bird's eye view game by the way. So the vehicles are seen from the top down.

You could use the transform.rotate method. The method uses an angle input, you could calculate the desired angle geometrically with your current orientation angle and the angle to the next waypoint.

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