- Home /
Velocity relative to Local Axis
Greetings,
Can I add velocity to an object relative to it's local axis?
This is the snippet of code:
rigidbody.velocity.z = MovSpeed;
But it's relative to the world, I want it to be relative to the local object.
Here is the full script.
private var lookRotationPoint = Vector3;
public var MovSpeed : float = 10.00;
function Update()
{
var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast(ray, hit))
{
if (hit.collider.gameObject.tag == "Plane")
{
var lookRotationPoint = hit.point - transform.position;
transform.rotation = Quaternion.LookRotation(lookRotationPoint.normalized);
transform.rotation = Quaternion.Euler(0, transform.rotation.eulerAngles.y, 0);
}
if(Input.GetMouseButton(1))
{
"Code goes here"
}
if(!Input.GetMouseButton(1))
{
rigidbody.velocity = Vector3(0,0,0);
}
}
}
Answer by aldonaletto · Dec 08, 2011 at 11:36 PM
Convert the current velocity to local space, modify the z component and convert it back to world space:
var locVel = transform.InverseTransformDirection(rigidbody.velocity);
locVel.z = MovSpeed;
rigidbody.velocity = transform.TransformDirection(locVel);
But if you just want to add/subtract a velocity in the forward direction, use transform.forward:
rigidbody.velocity += transform.forward * MovSpeed;
It works, but halfly. The velocity total doesn't follow the fix value and provoke a slingshot effect.
You're modifying only the z local component, what alters the magnitude and the direction; furthermore, transform.forward and rigidbody.velocity may have completely different directions - thus local space (a transform related concept) may not be what you're looking for.
What exactly do you want to do? $$anonymous$$odify the direction without changing the magnitude? Or keep the direction and modify the magnitude? Or none of above?
I want to move the object on a constant pace toward it's own rotation. Thus I want to control velocity through the script and keep it's x,z velocity equal to the $$anonymous$$ovSpeed variable.
I also thought of translating the Y rotation degree into X,Z distribution value (ie 90Y rotation = 0.5x + 0.5z), the distribute the total velocity wanted ($$anonymous$$ovSpeed) to the x and z velocity. But I'm not sure it's the best way to accomplish this.
I suppose that this may be what you're looking for:
rigidbody.velocity = transform.forward * $$anonymous$$ovSpeed;
If you rotate the object, transform.forward follow the direction change, thus this should do what you want. It's advisable to set rigidbody.freezeRotation to true - the object still can be rotated, but physics rotational effects will be disabled, avoiding weird reactions to collisions.
Yes, it behaves exactly how I wanted. Better then my patch-up where I've translated Y rotation to X,Z using Cos and Sin maths.
Erf, and just saw I've used a similar code in an old project, just didn't saw the relation.
Anyway, thank you very much sir.