- Home /
Simple go forward and turn back loop movement stuck to the limit without reverse
I have a game object placed at the position (0, 5, 80)
I want that this object ciclically moves foward (direction x in my orientation) and then when has reached a certain position turn back until has reached another limit position and so on .
It's a very simple task but unfortunately when the object reaches the stop to move and desn't change direction.
I have written this function called in Update
section
function cyclicMove(){
if(boat.position.x==-190){
boat.rotation.y=-90;
}
else if(boat.position.x==190){
boat.rotation.y=90;
}
else if(boat.position.x>-190){
boat.position.x--;
}
else if(boat.position.x<190){
boat.position.x++;
}
}
The object should turn in 190 and -190c continuing the movement in the other direction but for some reason this doesn't happen.
Any suggestion?
Answer by SMH17 · Jul 07, 2015 at 02:33 PM
Here the solution. When the boat rotate the movement coordinated are inverted. With this edit to the original code, now works.
function cyclicMove(limit:int, speed:int){
position=boat.position.x;
if(position <= -limit){
turnBack();
}
else if(position >= limit){
turnBack();
}
moveForward(speed);
}
function turnBack() {
boat.rotation.y=boat.rotation.y*-1;
}
function moveForward(speed:float) {
boat.position -= transform.forward * speed * Time.deltaTime;
}
Answer by Bluk · Jul 07, 2015 at 11:19 AM
function cyclicMove(){
if(boat.position.x <= -190){
boat.rotation.y=-90;
}
else if(boat.position.x >= 190){
boat.rotation.y=90;
}
else if(boat.position.x > -190){
boat.position.x--;
}
else if(boat.position.x < 190){
boat.position.x++;
}
}
It should do the trick. Be careful though that the last else if is not reached if you have for example boat.position.x = 0
Similar problem also with your code... the object doesn't reverse movement.
in addition the rotation coordinate y become 180 for some reason
Your answer
Follow this Question
Related Questions
javascript for animating/moving non humanoid generic 0 Answers
When i make my character animated, he can only move up, down left and right (2D) (JS) 0 Answers
Javascript Movement Script. Why am I getting these errors? 2 Answers
No animation attached to gameobject? 2 Answers
Trying to get a sword swinging animation to play on mouse button 1 (unity 5) 2 Answers