user16642652
user16642652

Reputation:

Debug.DrawRay() pointing to wrong direction in Unity2D

I am trying to learn how to Raycast in Unity2D.

Here is my code:

Ray ray;
void Update()
{
    ray = new Ray(transform.position, Input.mousePosition);
    Debug.DrawRay(transform.position,Input.mousePosition);
}

This results in strange behavior.
transform.position is the Vector3 of the player object.

I want to shoot a ray from the Player Object through the Mouse Position.

However, this does not seem to work.

The line is drawn, but behaves weirdly. It does not point toward it at all. It's hard to accurately describe its behavior as anything except erratic.

What am I doing wrong?

I think there may be something wrong with putting in Input.mousePosition and directions in general. I would be very thankful for any help you can give.

Note: I am using Unity 2D.

Upvotes: 1

Views: 723

Answers (1)

DekuDesu
DekuDesu

Reputation: 2292

When you use Input.mousePosition you get a Vector2 which represents the position of the mouse relative to the camera. This means the X and Y you get are actually the X and Y of the position of the mouse on the screen.

These coordinates are not world coordinates.

For example if you were to draw a ray from transform.position of a player standing at 0,0,0 to the mouse position of 500, 250 you would get a gigantic and seemingly randomly pointing ray.

Example Showing Screen Coordinates vs. World Coordinates

To convert from where the mouse is on the screen(Screen Coordinates) to what it's pointing to in-game(World Coordinates) you can use Camera.ScreenToWorldPoint.

For example

Ray ray;
void Update()
{
    // get the mouse screen pos
    Vector3 mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y);
    
    // convert it
    Vector3 worldMousePosition = Camera.Main.ScreenToWorldPoint(mousePosition);

    ray = new Ray(transform.position, );
    Debug.DrawRay(transform.position, worldMousePosition);
}

Upvotes: 1

Related Questions