- Home /
Physics2d.Linecast and Debug.drawLine result is strange.
Vector2 curMousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 mouseDir = curMousePosition * 10.0f;
RaycastHit2D hit = Physics2D.Linecast(player.transform.position, mouseDir);
if (hit.collider != null)
{
Debug.Log("cur mouse point = " + curMousePosition);
Debug.Log("mouse dir point = " + mouseDir);
Debug.Log("hit point = " + hit.point);
Debug.DrawLine(player.transform.position, curMousePosition, Color.red);
Debug.DrawLine(player.transform.position, mouseDir, Color.yellow);
Debug.DrawLine(player.transform.position, hit.point, Color.blue);
}
The red line is from the player to the current mouse coordinates.
The yellow line is from the player to the current mouse coordinate multiplied by 10.0f.
The blue line is from the player to the Collider Hit coordinate.
My intention is to draw the Linecast to the coordinates of the mouse coordinate multiplied by 10.0f, A yellow line is drawn on the extension line of the red line, and there is also the Collider, so we expected to return the Collider coordinates on the extension line of the red line.
However, the result of [Mouse coordinate multiplication 10.0f] and [HIT POINT] is strange
I understand that to understand Linecast, I draw a hypothetical line between two other coordinates and return it if there is a Collider.
Am I misunderstanding something?
[1]: /storage/temp/109591-1.png
Answer by seung_il_park · Jan 20, 2018 at 07:40 PM
I was confused by the vector calculation.
I solved it with the code below.
Vector2 playerPos = player.transform.position;
Vector2 curMousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 relativePos = curMousePosition - playerPos;
float mouseAngle = Mathf.Atan2(relativePos.x, relativePos.y) * Mathf.Rad2Deg;
Quaternion rot = Quaternion.Euler(0f, 0f, -mouseAngle);
Vector2 rVec = rot * Vector2.up * 20.0f;
Vector2 mouseDir = playerPos + rVec;
RaycastHit2D hit = Physics2D.Linecast(player.transform.position, mouseDir);
if (hit.collider != null)
{
Debug.DrawLine(player.transform.position, mouseDir, Color.yellow);
Debug.DrawLine(player.transform.position, hit.point, Color.blue);
Debug.DrawLine(player.transform.position, curMousePosition, Color.red);
}
Your answer

Follow this Question
Related Questions
Inconsistent gravity/random forces/solver problem? (forum crosspost) 0 Answers
How do i stop rigidbody2D bounce 1 Answer
2D Box Colliders Overlapping On Collision 4 Answers
2D Water in Unity 0 Answers
Velocity.normalize to a min of one 3 Answers