C# script making GameObject move from point A to point B and rotate at the same time.

Content not available.
Please allow cookies by clicking Accept on the banner

 

using UnityEngine;
using System.Collections;

// ? 2016 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

public class MoveAndRotate : MonoBehaviour {
    public float speed;
    public GameObject pointA;
    public GameObject pointB;
    public bool reverseMove = false;
    private float startTime;
    private float journeyLength;
    public Vector3 Angles;


    // Use this for initialization
    void Start()
    {
        startTime = Time.time;
        journeyLength = Vector3.Distance(pointA.transform.position, pointB.transform.position);
    }

    // Update is called once per frame
    void Update()
    {
        float distCovered = (Time.time - startTime) * speed;
        float fracJourney = distCovered / journeyLength;

        transform.Rotate(Angles * Time.deltaTime); //Rotate GameObject

        if (reverseMove)
        {
            transform.position = Vector3.Lerp(pointB.transform.position, pointA.transform.position, fracJourney);
        }
        else
        {
            transform.position = Vector3.Lerp(pointA.transform.position, pointB.transform.position, fracJourney);
        }
        if ((Vector3.Distance(transform.position, pointB.transform.position) == 0.0f || Vector3.Distance(transform.position, pointA.transform.position) == 0.0f)) //Checks if the object has travelled to one of the points
        {
            if (reverseMove)
            {
                reverseMove = false;
            }
            else
            {
                reverseMove = true;
            }
            startTime = Time.time;
        }
    }
}

 



Unity C# Moving and Rotating GameObject
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close