Reputation: 1
I need to make the object move around the scene and jump, but every time the object rotates it changes the axis of motion. How can I ensure that the rotation of the object does not influence its movement?
public float forca = 300f;
public Rigidbody2D Bola;
public float movdir = 5f;
public float moveesq = -5f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Bola.AddForce(new Vector2(0, forca * Time.deltaTime), ForceMode2D.Impulse);
}
if (Input.GetKey(KeyCode.RightArrow))
{
Bola.transform.Translate(new Vector2(movdir * Time.deltaTime, 0));
}
if (Input.GetKey(KeyCode.LeftArrow))
{
Bola.transform.Translate(new Vector2(moveesq * Time.deltaTime, 0));
}
Upvotes: 0
Views: 131
Reputation: 90630
transform.Translate
takes an optional parameter relativeTo
with a default value Space.Self
→ movement in local X-axis
If
relativeTo
is left out or set toSpace.Self
the movement is applied relative to the transform's local axes. (the x, y and z axes shown when selecting the object inside the Scene View.) If relativeTo isSpace.World
the movement is applied relative to the world coordinate system.
You can convert this into the global X-axis (independent from the objects orientation) by simply passing Space.World
as last parameter:
if (Input.GetKey(KeyCode.RightArrow))
{
Bola.transform.Translate(new Vector2(movdir * Time.deltaTime, 0), Space.World);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
Bola.transform.Translate(new Vector2(moveesq * Time.deltaTime, 0), Space.World);
}
AddForce
however takes world space coordinates anyway so there you already are independent of the objects orientation.
However, since there is a rigidbody involved you should not set the position using the Transform
component at all. You should rather go through Rigidbody2D.MovePosition
if (Input.GetKey(KeyCode.RightArrow))
{
Bola.MovePosition(Bola.position + Vector2.right * movdir * Time.deltaTime);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
Bola.MovePosition(Bola.position + Vector2.right * moveesq * Time.deltaTime);
}
Yoi should this then rather also in FixedUpdate
Upvotes: 1
Reputation: 15941
Multiply by transform.forward
Currently your movement vectors are in absolute coordinates. You want them in local coordinates. The easiest way to do this is to multiple by transform.forward
(for forward motion) and transform.right
(for strafing motion).
Upvotes: 0