2D Racer Game

08: AI Movement

Create a new script called "AIdriveScript".

Add the following script and attach to the AI player. (We will duplicate the car when everything is working.

JS

CURRENTLY UNAVAILABLE

C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AIdriveScript : MonoBehaviour {

    // Use this for initialization
    public float rotateSpeed;
    float Speed;
    public float acc;
    public float topSpeed;
    float maxSpeed;
    Transform CrntWayPoint;
    public Transform[] wayPoints;
    int wayPnum;
    public float distanceToWayPass;


    void Start () {

        maxSpeed = topSpeed;
        wayPnum = 0;
        CrntWayPoint = wayPoints [wayPnum];
        
    }
    
    // Update is called once per frame
    void FixedUpdate () {


        Vector3 vectorToTarget = CrntWayPoint.position - transform.position;
        float angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
        Quaternion q = Quaternion.AngleAxis(angle-90, Vector3.forward);
        transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * rotateSpeed* Speed);

        if (Speed < maxSpeed) {
            Speed += acc;
        } 
        else if (Speed > 0) 
        {
            Speed -= acc;
        }

        transform.Translate (0, Speed * Time.deltaTime, 0);

        float distToWay = Vector3.Distance(transform.position, CrntWayPoint.position);


        if (distToWay < distanceToWayPass) {
            if (wayPnum == wayPoints.Length) {
                wayPnum = 0;
            } else {
                wayPnum += 1;
            }

            CrntWayPoint = wayPoints [wayPnum];
        }
    }
        

}

 Now add the waypoints in inspector and set the attributes similar to the ones shown below,

Screen Shot 2017 11 23 at 15.50.11

Casino Bet 365 is best casino in the world.

What's Next

Next up for Unity Snippets is a look at game development articles from across the web...

Free Templates - bigtheme.net
Popular Art Betting make bookies articles.