is it possible for velocity vectors to be added on the players axis?
Hi, I have been using this line of code to add force to my rigidbody player.
GetComponent.<Rigidbody>().velocity += Vector3.right * sideSpeed;
the only problem is that it only works in one particular direction. So, say if i was facing north, and i press a key that executes this function. And the player jumps right. If i was to face East, the command would shoot me backwards. Is there a way so that in any direction the player faces they will always jump to their right? Thanks.
Answer by _dns_ · Nov 17, 2015 at 03:36 PM
Hi, use transform.right or transform.forward : those are vectors that are expressed in your object local space = always forward or right relative to your object, not absolute values in world space like Vector3.right.
And a reminder: always modify an object physics properties during FixedUpdate :)
Sure and Unity makes it very simple. Ins$$anonymous$$d of Vector3.right use Transform.right.
(converted to a comment)
Well, that's not some Unity complexity here, that's how a hierarchy of 3D object works. Vector3.forward is a constant from the Vector3 class and it's expressed in world space. if you want that some force pushes an object in one direction regardless of it's own rotation, add Vector3.forward to it's velocity (like some wind force).
If you want the object to go "in front" of itself, you need to take in account it's rotation in the world, and the rotation of it's parents (if any). That's why you have to use the transform component of this object to compute his local forward vector. Note that's is "transform.forward", so the object's transform component's "forward" and not "Transform.forward" that would be a constant from the Transform class like Vector3.forward is.
Thanks dude, this work brilliantly! I eventually figured out to go left would be to use -transform.right. Is it possible to do this for the command rigid body .AddForce? Like addforce to the right / left? Thanks guys
yes, using Rigidbody.AddForce is a more abstract way than modifying velocity. You just don't need to multiply forces by deltaTime (ho, just realize that you may not do that yet, so better use AddForce to be framerate-proof). Check the different Force$$anonymous$$ode you can use in the documentation to get the result you want.
Would something like this work?
gameObject.rigidbody.AddForce(transform.right * force)
thanks dns, you have been such a help for me. The way you answer questions comes across in a very polite manner. Thanks for putting up with me!