Problem with local position

Hey guys,

I am trying to lock my objects position on its local y and z coordinates letting it still move on its local x axis.

The problem is that when these are used it makes them world coordinates meaning the object doesn’t move at all when its local x isn’t aligned to the world x axis.

function Start(){
	lockedPosition = Vector3(transform.localPosition.x,transform.localPosition.y,transform.localPosition.z);

function Update () {
	transform.localPosition = Vector3(transform.localPosition.x,lockedPosition.y,lockedPosition.z);

Thanks in advance

localPosition gives coordinates in your parent’s local space. If you don’t have a parent, it’s the same as position.

To get your local x-axis (for example,) use transform.right, which is a shortcut for transform.TransformDirection(Vector3.right)); (and V3.right is just a shortcut for (1,0,0).) For example:

transform.position += mvAmt * transform.right; // move L/R on my local axis

If you need it be be a rigidbody, moving on just one arbitrary axis, you could hand-tweak velocity (and pos, maybe) using the “local frame of reference” trick, to only be along your x.

Unity uses world coords for most things. Local coords are for the programmer to “think in.” The most common opertations – transform.right or transform.TransformDirection(V3.right); convert from local “thinking” coords to useful world coords. To take that one step further, to fix velocity, which is in world coords, convert to useless local coords, fix it to go along the line, then convert back:

// compute local velocity:
Vector3 Lvel = tranform.InverseTransformDirection(rigidbody.velocity);

Lvel is still your velocity, but in terms of your personal little red/green/blue arrows (which Unity can’t use.) Suppose Lvel is (4,0,1). That means your speed is your sideways +4 and your forward +1. You want speed to only be sideways, so kill the y and z:

Lvel.y = Lvel.z = 0;

Now you have velocity in useless local coords, but just convert back the regular way:

rigidbody.velocity = transform.TransformDirection(Lvel);

Or, instead of those two lines, just: ridigbody.velocity=transform.right*Lvel.x;

This could go in FixedUpdate (maybe OnCollisionLeave, so you only fix velocity after something changed it.)

Each bump will probably knock your guy a little off his personal L/R axis. A similar trick can put him back. Make an empty to establish the line, subtract and InvTrans to get local, zero out y and z, trans and add to go back.

Hello i have come across velocity.project that is used to make an object act like its on a rail which sounds like what you want.

this is what i followed

and infortation in the script reference

i know this is an old post but it might help some else who comes across this thread like me.