- Home /
transform.position question
Hi guys. :) my question is: how can I do for move a transverse object Up and Down with transform position? i posted a pic. This way is wrong? It's convenient make the object straight and after change its position?
#pragma strict
public var GameObject : Pistone;
function Update () {
if(Input.GetKeyDown(KeyCode.A)) {
Pistone.transform.position = Vector3(0,0,0);
}
}
Answer by robertbu · Jun 22, 2014 at 04:54 PM
Assuming the object is a child of the rod, and that you aligned the two before the whole thing is rotated, you can just use Transform.localPosition for the movement. Alternately, you can use Transform.Translate(). Translate() uses local coordinates by default.
Ok, but the piston dosn't move Up and Down, but transversely.
var move : float = 0.1;
var translation : float;
function Start () {
}
function Update () {
if(Input.Get$$anonymous$$ey($$anonymous$$eyCode.A)) {
translation = Time.deltaTime * move;
transform.Translate(new Vector3(0,1,0) * translation);
}
if(Input.Get$$anonymous$$ey($$anonymous$$eyCode.S)) {
translation = Time.deltaTime * move;
transform.Translate(new Vector3(0,-1,0) * translation);
}
}
You are moving it on the local 'Y':
transform.Translate(new Vector3(0,1,0) * translation);
This means that your rotation is not what you expect. It could be for several reasons, but the most likely is that you constructed your child horizontally and have it rotated with respect to the parent. So you can fix it in a couple of different ways. First, just pick the local axis that does move it up and down the rod. It will be 'x' or 'z'. Or you can go back and rotate your object in your modeling program. If you are looking for easy 'y' movement, you want both the rod and the object to be vertical when their rotations are (0,0,0).
When I move the piston Up with local axis (in the scene), in the transform change the 'Y' position, for this reason I set (0,1,0). And now? I have to straighten the piston, set the code when the piston is straight, and after incline it?
I'm assu$$anonymous$$g your rod is a Unity Cylinder that is vertical when the rotation is (0,0,0). In order to move your cylinder on the local 'Y' axis, and have it move up and down the rod, your cylinder has to also be constructed so that when you import it from your modeling program, it is vertical when the rotation is (0,0,0). As an alternate to my two suggestions above, you can also solve the problem by making the cylinder a child of an empty game object.
So I have to create a empty game-object, and put into it the piston?
Your answer
