- Home /
Object moving but not only on the axis i want
If i touch a button, it executes this function:
function move_y(howmuch : int){
if(howmuch > 0 && object.transform.localPosition.y<10)
object.transform.Translate(Vector3.up, Space.World);
if(howmuch < 0 && object.transform.localPosition.y>0)
object.transform.Translate(Vector3.down, Space.World);
}
The problem is, that the object is not moving only on the Y axis, but on X and Z axis too and slightly rotates on the Y axis. What can be the problem?
I think, the above script is making no sense at all. Since you are defining the variable "howmuch" in the function. But you never initialized it. And you are giving it in the condition at the same time!
Or is the variable "howmuch" relevant to the position?
howmuch is passed in on the function call:
move_y(2); //example
no need for an int here, but it's obviously a learning attempt
Of course, I know that. But what is the purpose of it? It is nothing but hard-coding! If he passes a positive number, only one condition will be executed.
That is why I asked, is the variable "howmuch" related to position?
It is working fine for both object.transform.localPosition.y
and object.transform.position.y
.
Answer by Seth-Bergman · May 02, 2012 at 10:44 AM
A few issues I see off the bat:
you probably don't want localPosition, try object.transform.position.y
if you just want to go straight up and down, you could say:
object.transform.position.y += howMuch;
if you want smooth movement though, better to use something like:
object.transform.position.y = Mathf.Lerp(object.transform.position.y, howMuch);
this would of course need to be called continuously, so maybe get that part into the update function.
maybe could be that physics are affecting the object, if it has a rigidbody
edit:
the easiest way I can think of to accomplish what you seem to want:
function Update()
{
if(Input.GetKey("Fire1") && object.transform.localPosition.y<10)
object.transform.position.y = Mathf.Lerp(object.transform.position.y, 10,Time.deltaTime);
if(Input.GetKey("Fire2") && object.transform.localPosition.y>0)
object.transform.position.y = Mathf.Lerp(object.transform.position.y, 0,Time.deltaTime);
}
i've deleted the rigidbody from the object (it was set not to use gravity and it was kinematic, so i don't know what was the problem) and this way it seems like it is working now with the "object.transform.position.y += how$$anonymous$$uch" method.
if it was set to is$$anonymous$$inematic it wouldn't have mattered, I was just throwing out a possibility.. At any rate, is that what you were after (with what you have)?