- Home /
Question by
trecani96 · Oct 15, 2014 at 03:39 PM ·
javascripttransformobject
Move object back automatically
public var goTransform:Transform;
private var vel:int = 2;//how fast the game object is being moved
function Awake()
{
//get this GameObject's Transform
goTransform = this.GetComponent(Transform);
}
// Update is called once per frame
function Update()
{
//moves the containing GameObject forward
goTransform.position.z = goTransform.position.z + vel;
}
with this script you can make an object move forward automatically.
What should I change to get the object back in the opposite direction?
Comment
Answer by fafase · Oct 15, 2014 at 03:47 PM
You can use:
http://docs.unity3d.com/ScriptReference/Mathf.PingPong.html
or a sin/cos fct since they are naturally going from -1 to 1 and on again non stop.
Final way is lerping either with Mathf.Lerp/MoveTowards or Vector3.Lerp/MoveTowards. Those require that you check if you reach the target then set it back to the opposite one:
var target:Transform[];
var index : int = 0;
var ratio : float = 0.5f;
function Update()
{
if(transform.position == target[index])
{
if(++index == target.Length)
{
index = 0;
}
}
transform.position = Vector3.Lerp(transform.position, target[index], ratio * Time.deltaTime);
}
Your answer
Follow this Question
Related Questions
Move object to raycast point. 3 Answers
Object instantiation Logic Javascript. 1 Answer
Run through hastable of objects 1 Answer
Type 'Object' does not support slicing 1 Answer
Best Way to make a character move 1 Answer