Speed Gate

So I’ve got this script applied to a trigger gate for when the player (being a trigger) passes the gate, the player flings across to the target:

var target : Transform; //a null point where the Player goes to

var speed : float; //how fast

var hitgate : boolean; //if the player has hit that gate

var Player : GameObject; //The Main Player

function Start () {

hitgate = false;

}

function OnTriggerEnter () {

hitgate = true;

}

function Update () {

var step = speed * Time.deltaTime;

if (hitgate==true) {

//Move Player Sequence

Player.transform.position = Vector3.MoveTowards(transform.position, target.position, step);

}

}

Now the weird part is when the player touches the gate, it gets stuck in the gate position and stays. If I change the speed to 1000, the player is rapidly (at a very fast rate) flung to the target and back and to and back constantly. What is going wrong? Have I got some sort of loop thing in the script? How do fix this?

1 Answer

1

You have 2 problems:

1. hitgate value

hitgate is never set back to false at all, so you will run the MoveToward() in every Update() once the hitgate = true

2. Logic error

//Incorrect
// That's why your player are stuck because transform.position (the gate)
// and target.position (the landing zone) never changes
Player.transform.position = Vector3.MoveTowards(transform.position, target.position, step);

//Correct
Player.transform.position = Vector3.MoveTowards(Player.transform.position, target.position, step);

Fixing these 2 should solve your problem.

That is amazing! How do I make it so that after 1 second it stops trying to take the player to the target? I tried placing a yield WaitForSeconds (1); hitgate = false; after the Vector3.MoveTowards line. It didn't work. It would also be a bonus if you could tell me why that didn't work.

–

yield will not work in Update() [(Reference)][1]. You need to put the yield in a function. Furthermore, instead of calling the yield-function in Update, you can do it in OnTriggerEnter: function OnTriggerEnter () { hitgate = true; CloseHitGate(); } function CloseHitGate() { yield WaitForSeconds (2); hitgate = false; } [1]: http://docs.unity3d.com/Documentation/ScriptReference/index.Coroutines_26_Yield.html

–

Thank you for that knowledge but I just realized it would be much easier if I state in the script once it gets to the target, hitgate=false. How would you suggest I do this?

–

Check the distance between the target and the player: if( Vector3.Distance( Player.transform.position, target.position ) < 0.5f ) { hitgate = false; }

–

It worked! It worked! Thank you Chronos!

–