- Home /
Moving Object up and down without player input (such as a spike that kills you)
Hello. Currently I'm trying to move an object up and down with if statements on the y axis. The object is a spike that if the player touches dies.
This is the script I'm using. I want to have the spike move up to a certain point on the y axis and when it hits it to move down until it hits another point and then have it move up again. It's probably worth noting that i have the spike attached to an empty game object so its starting position is always 0.
function Update() {
if (this.transform.position.y <= 0){
this.transform.position.y = this.transform.position.y + (10*Time.deltaTime);
}
if (this.transform.position.y >= 10){
this.transform.position.y = this.tranform.position.y - (5*Time.deltaTime);
}
}
function OnTriggerEnter (other :Collider){
Application.LoadLevel("Game Over");
}
Right now this script will move the spike up 10 on the y axis but then it will stop there and not go back down. Any help would be greatly appreciated !
Answer by Muuskii · Jul 11, 2012 at 02:59 AM
Right now you have two if statements, one is only done when the spike is at the bottom of it's course and the other only at the top. You have nothing for in between. You need to do something more like:
float velocity = 10;
transform.position.y -= velocity * TimedeltaTime;
if(transform.position.y >= 10)velocity = -5;
else if(transform.position.y <= 0)velocity = 10;
You don't need the this keyword before transform and you need a way for the program to remember what it's doing between waypoints
Answer by VIPINSIRWANI · Sep 18, 2013 at 12:07 PM
start = new Vector3(0,0,0);
target= new Vector3(4,0,0);
void Update () {
Vector3 pos = transform.position;
if(pos != target)
{
transform.position = Vector3.MoveTowards(pos,target,0.03f);
}
else
{
target = start;
if(pos == start)
{
target = new Vector3(4,0,0);
}
}
Your answer
Follow this Question
Related Questions
Perpendicular Vector3 0 Answers
physics question my object setup failing collision 3 Answers
GameObject automatically moves up when upgrade is purchased. 2 Answers
Knowing when mouse has been released 2 Answers
GUI begin vertical, to go Up 1 Answer