- Home /
Question by
Varlac · Jun 04 at 09:06 AM ·
2dgameobjectphysicsrigidbody2d
How can I move a 2D GameObject left/right relative to its forward direction?
So far, I have this code which seems to work fine, but I'm not sure how to move it left or right relative to forward direction, being the position of mouse cursor.
void Update () {
dir = Input.mousePosition - mainCamera.WorldToScreenPoint(transform.position);
dir.Normalize();
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.eulerAngles = Vector3.forward * angle;
mainCamera.transform.position = new Vector3(rb.position.x, rb.position.y, -10);
}
void FixedUpdate() {
Vector2 velocity = new Vector2();
if(Input.GetKey("w")) velocity = dir * 5;
if(Input.GetKey("a")) // how???
if(Input.GetKey("d")) // how???
rb.velocity = velocity;
}
Comment
Answer by DockAnkh · Jun 04 at 02:17 PM
A few things: what do you mean by left and right here? I assume you don't want it to turn left or right since it will be facing the mouse. To add force relative to how the the object is facing I believe Vector3.left or Vectror3.right will do that. Similar to how you use Vector3.forward.
You also probably don't want to be checking for an input key in FixedUpdate. Input is checked every frame so you want to check in Update and then use what you find in Update in FixedUpdate. This will save you problems down the line.