- Home /
How to check if mouse is above or below player?
Hello there! I have been working on a top down 2D roguelike with action combat. The player attacks in the direction of the mouse click. I know that if you want to check if the mouse is to the left or to the right of the player you have to do something like if(mousePosition.x > player.transform.position.x) and the other way around for the right. Now the problem i am having is how do i detect if the mouse was pressed above or below the player and how do i check in an if chain if the mouse was pressed to the right, left, up or down? Thanks in advance!
Answer by Llama_w_2Ls · Jul 27, 2020 at 05:11 PM
public Camera cam;
public GameObject player;
void Update()
{
if (Input.GetMouseButtonDown(0)) //if i left click
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 Ray = ray.direction;
RaycastHit hit; //raycasts need to hit solid objects to detect a hit
if (Physics.Raycast(cam.transform.position, Ray, out hit)) //Shoot a raycast from my camera to where i clicked
{
if (hit.point.x < player.transform.position.x)
{
//I clicked on the left side of the player
}
else if (hit.point.x >= player.transform.position.x)
{
//I clicked on the right side of the player
}
}
}
}
I dont know if raycasts work for 2D but here goes anyway
@Llama_w_2Ls hey thanks for the answer. The problem is that i need to check if it is above or below not left or right. If you could help me with that by integrating below and above in the code you wrote i would really appreciate it. Have a nice day!
public Camera cam;
public GameObject player;
void Update()
{
if (Input.Get$$anonymous$$ouseButtonDown(0)) //if i left click
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 Ray = ray.direction;
RaycastHit hit; //raycasts need to hit solid objects to detect a hit
if (Physics.Raycast(cam.transform.position, Ray, out hit)) //Shoot a raycast from my camera to where i clicked
{
if (hit.point.y < player.transform.position.y)
{
//I clicked above the player
}
else if (hit.point.y >= player.transform.position.y)
{
//I clicked below the player
}
}
}
}
@Llama_w_2Ls Thanks it worked! How would i go about combining the two scripts you wrote so i can have it go around the player: left, right, above and down?
Answer by SeDevr · Jul 27, 2020 at 07:11 PM
i dont know exactly, but i think you can find some data on this if you search for the keycodes online( i dont know if that helps)
Your answer
Follow this Question
Related Questions
Unity2D Pixels deforming when moving 0 Answers
Horrible lag in 2d roguelike character movement 6 Answers
How do I make my character move on the Z axis on 2d rigidbody? 0 Answers
How in the world do I ACCURATELY place an object at the mouse? 3 Answers
[2D] Enable colliders around the player based on the direction of the mouse click 1 Answer