Raycast2D not working like it should be.
Hello everybody. I currently have a question. I am creating an 2d rts game. I am using OnMouseOver() to select units. Now I am working on the right-click-to-move mechanic. Unfortunately, I am having weird problems with Raycast2D. Here is a script I wrote:
void OnMouseOver(){
if (Input.GetMouseButtonDown (0)) {
isSelected = true;
Debug.Log ("" + transform.name + " was selected");
}
}
void Update(){
if(Input.GetAxis("Cancel")>0){
isSelected = false;
Debug.Log ("" + transform.name + " was deselected");
}
if (isSelected) {
if (Input.GetMouseButtonDown (1)) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction, Mathf.Infinity);
Debug.Log ("Unit" + transform.name + "has detected a command to go to" + hit.point + "");
}
}
}
}
When I run the script, the OnMouseOver() part works perfectly, however, the Raycast2D does not work. When I right-click somewhere on the scene, the debug.log message just says that the unit has been ordered to go to the 2D origin (0.0, 0.0). However, one weird thing is that if I right click on another unit, it gives me correct coordinates.
P.S.: I know I did not make it as clear but I did put a collider on the gamefield, so in theory if I click anywhere on the map, I should get a valid value for hit.point.
Your answer
Follow this Question
Related Questions
Is there any way how to do raycasts like this? 0 Answers
2D Raycast reflection only changes hit.normal 0 Answers
Select Object And Spawn it 1 Answer
Im trying to make an RTS camera that would pan in the direction of the mouse instead of an axis 1 Answer
Finding unique interacting function within gameObject 0 Answers