- Home /
Getting an Objects position once
Hello,
I am having an issue in getting a value once. Basically I am trying to move a platform back and forth a certain distance. The plat form does not start at x = 0, therefore if I place the object at x = 30, and I ask it to go +20x and return to 0 it will end up travelling from 50x back to 0. I have tried to make it so I ask it to go 20 + transform.position.x, but that ends up making it go on forever. I know I am bad at explaining things so here is the code I am using so far, any help is much appreciated. Thanks.
var elevatorDirection : Vector3 = Vector3.left;
var height;
var Distance = 10;
var speed = 5;
height = Distance + transform.position.x;
function Update(){
transform.position -= elevatorDirection * Time.deltaTime * speed;
if(transform.position.x < height) {
elevatorDirection = Vector3.left;
}
if(transform.position.x >= height) {
elevatorDirection = Vector3.right;
}
}
Answer by aldonaletto · Jun 13, 2012 at 11:26 PM
You should save the initial position at Start, and base all movements on it:
var elevatorDirection : Vector3 = Vector3.left; var height: float; // specify the variable type when there's no initial value var Distance = 10; var speed = 5; var pos0: float; // holds the initial X coordinate
function Start(){ pos0 = transform.position.x; // register the initial position in pos0 }
// always specify the distance added to pos0:
height = Distance + pos0;
function Update(){ transform.position -= elevatorDirection Time.deltaTime speed;
if(transform.position.x < height) {
elevatorDirection = Vector3.left;
}
if(transform.position.x >= height) {
elevatorDirection = Vector3.right;
}
} But there's a better way to do what you want:
var elevatorDirection : Vector3 = Vector3.left; var Distance = 10; var speed = 5; var dest: Vector3; // holds the desired position var pos0: Vector3; // holds the initial position
function Start(){ pos0 = transform.position; // register the initial position in pos0 }
// always specify the destination relative to pos0:
dest = pos0 + Distance * Vector3.right;
function Update(){ transform.position = Vector3.MoveTowards(transform.position, dest, Time.deltaTime * speed); } MoveTowards takes care of determining to which direction move in order to reach the destination (the 2nd parameter), and never passes beyond it.
Answer by Fehr · Jun 13, 2012 at 11:32 PM
Try this:
function Update(){
transform.position += elevatorDirection * Time.deltaTime * speed;
if(transform.position.x > height) {
elevatorDirection = Vector3.left;
}else if(transform.position.x < 0){
elevatorDirection = Vector3.right;
}
}
Your answer
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
Vector3 Transform.Position Not Working 2 Answers
Position of a GameObject 2 Answers
Change object position on trigger enter 3 Answers