- Home /
Clamping Velocity.z when touching an object (Major Edit)
Major edit to reflect new approach to problem:
I am currently in the process of creating a 3d 1st person character. I'm currently having a problem with jumping and obstacles, and am attempting to prevent the character from being able to move forward when he is touching an obstacle (all other directions are ok).
My inital code was as follows:
if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward), 0.6f)) {
rigidbody.velocity = new Vector3 (
rigidbody.velocity.x,
rigidbody.velocity.y,
Mathf.Clamp(rigidbody.velocity.z, -100, 0));
}
This worked pretty well, however it only worked in global space, I.E when my character's idea of "forward" was along the positive direction of the z axis. Any other way and it doesn't work.
I then tried:
if (Physics.Raycast (transform.position, transform.TransformDirection (Vector3.forward), 0.6f)) {
rigidbody.velocity = transform.TransformDirection(
rigidbody.velocity.x,
rigidbody.velocity.y,
Mathf.Clamp(rigidbody.velocity.z, -100, 0));
}
This doesn't work either, I get some kind of insane push in the negative global Z direction whichever way I am facing, so it only works on obstacles that are in front of me in global space as well as local space. It also makes my x directions swap around.
InverseTransformDirection doesn't work either.
Halp?
I think you should check out this bud. It will help you understand how to control the local Positions over the world space positions. In any case, you are only making the call to .localPosition
ins$$anonymous$$d of plain old .position
It might be best to make sure you check your local position is set correctly firstly by switching to "local" ins$$anonymous$$d of "Global" through the tab button found near the top left of your editor window (the axis controls bit)
Answer by robertbu · May 04, 2014 at 01:36 PM
In order to make this work, you have to first convert velocity into local space, do the clamp, then convert the velocity back to global space. Something like:
if (Physics.Raycast (transform.position, transform.forward, 0.6f)) {
Vector3 localDir = Transform.InverseTransformDirection(rigidbody.velocity);
localDir.z = Mathf.Clamp(localDir.z, -100, 0);
rigidbody.velocity = Transform.Tranform.TransformDirection(localDir);
}
Your answer
Follow this Question
Related Questions
Local Velocity for Rigidbody? 1 Answer
How do I make rigidbody.velocity in local space? 1 Answer
Global/local axis hotkey 2 Answers
Vertex Coordinates to Global Vector3 2 Answers
Local vs Global Transform 1 Answer