- Home /
Relative and absolute values problem
Hello everyone. I have an object which is randomly instantiated on the x axis at a position between x = - 4 and x = 4. Once it is instantiated i would like it to start a loop movement between x = - 4 an x = 4. I've used the Mathf.PingPong function but it doesn't work since this function creates a movement from the relative starting position to another relative point and back to the starting position. I need to set the absolute world values - 4 and 4. I tryed using Mathf.Clamp as argument for the Mathf.PingPong function but it didn't work either. This is the code i'm using:
transform.position = transform.position + Vector3(Mathf.PingPong(Time.time, 8), 0, 0);
I thought about a solution but something doesn't work: i tryed to create two planes with colliders and rigid bodies and put them at x = - 4 and x = 4, i applied a tag "Limit" to them. Then i wrote this code and attached to the object that should move between the two x values:
function OnTriggerEnter (col : Collider){
if(col.gameObject.tag == "Limit"){
transform.position.x = -transform.position.x;
}
}
I though that this way when the object hits a plane should change its x direction and start moving the opposite way. But when i start the game and the object hits a plane doesn't happen anything at all. Something must be wrong, can you help me?
Answer by Eric5h5 · Jul 13, 2012 at 12:16 AM
You can create a variable and update that via Time.deltaTime.
private var pos : float;
function Start () {
pos = Random.Range (0.0, 8.0);
transform.position.x = pos - 4.0;
}
function Update () {
pos += Time.deltaTime;
transform.position.x = Mathf.PingPong (pos, 8.0) - 4.0;
}
Answer by Ingen · Jul 13, 2012 at 12:18 AM
take a look at
http://docs.unity3d.com/Documentation/ScriptReference/Mathf.Lerp.html
http://docs.unity3d.com/Documentation/ScriptReference/Transform.Translate.html