How can i move object between two positions ?
I want to move the object between the distance 0 and 100. move it to the right when the distanceTravelled is get to 100 change direction. When it's getting to 0 again change direction again and so on.
And second option i want to make that when the distanceTravelled is got to 100 change direction and then when the object is getting to it's originalPosition change direction again.
How can i make this both cases ? ( Each case alone but how to make them ? i mean same script but each time with the other option)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveObject : MonoBehaviour {
public float moveSpeed = 2.0f;
private float distanceTravelled;
private Vector3 originalPosition;
// Use this for initialization
void Start ()
{
originalPosition = transform.position;
}
// Update is called once per frame
void Update()
{
distanceTravelled += Vector3.Distance(originalPosition, transform.position);
if (distanceTravelled < 100f)
transform.Translate(Vector3.right * moveSpeed * Time.deltaTime);
if (distanceTravelled >= 100f)
{
transform.Translate(Vector3.left * moveSpeed * Time.deltaTime);
}
}
}
Answer by Menyus777 · Aug 05, 2017 at 10:15 AM
public static Vector3 MoveTowards(Vector3 current, Vector3 target, float maxDistanceDelta);
https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html
You set up 2 Vectors, this way you make the two endpoints you would like to move your object, When movetowards reaches its target it'll return its Destination.
Vector3 Destination = new Vector3(0,0,100);
Vector3 Traveller = new Vector3(0,0,0);
float step = 2.5f;
while(Traveller != Destination){
Traveller = Vector3.MoveTowards(Traveller, Destination, Step);
}
I reccomend you to implement this in a Coroutine.
Your answer
Follow this Question
Related Questions
How can i disable/enable slowly the blur effect using the blur script ? 0 Answers
How can I give each instance a enum mode from another script ? 0 Answers
How can i make the right choice of implementation of my shooting fire script ? 1 Answer
How can i set the camera to be automatic behind the player ? 0 Answers
can i get help please 0 Answers