Search code examples
c#unity-game-engine2dtop-down

Unity 2D Top-Down Raycasting


I am trying to make 2D top-down shooter, and I can't figure out how to do a raycast. I don't know what to put for the second parameter- the direction. I've tried Input.mousePosition, and some other things I've seen on StackOverflow, but I can't seem to make anything work. Here is my code on my player character.

//Raycasts
var forward = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, 0);
Debug.DrawRay (transform.position, forward * 10, Color.green);

//Mouse Movement
Vector3 mousePos = Input.mousePosition;
mousePos.z = 5.23f;
Vector3 objectPos = Camera.main.WorldToScreenPoint (transform.position);
mousePos.x = mousePos.x - objectPos.x;
mousePos.y = mousePos.y - objectPos.y;
float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(new Vector3(0, 0, angle - 90));


//Player Movement
if (Input.GetKey (KeyCode.D)) {rigidbody2D.AddForce(Vector3.right * speed);}
if (Input.GetKey (KeyCode.A)) {rigidbody2D.AddForce(Vector3.left * speed);}
if (Input.GetKey (KeyCode.W)) {rigidbody2D.AddForce(Vector3.up * speed);}
if (Input.GetKey (KeyCode.S)) {rigidbody2D.AddForce(Vector3.down * speed);}

Is there something I can reuse from my Mouse Movement part of the script to do the direction part of the raycast?

Thank you so much for the help!


Solution

  • It could be a good idea to get to know some vector math for game programming.

    In your case what you want is a vector that is pointing from the player position to the mouse position. You can compute this as Erno de Weerd mentioned in comments by calculating

    // shootDirection = mousePosition - playerPosition
    Vector3 shootDirection = Input.mousePosition - transform.position;
    

    This is equivalent of moving backwards from player position to origin and forward from origin to mouse position.