- Home /
Detect Mouse in right side or left side For Player?
Hello, i use this code to detect Moues Position
mouse = new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y);
if(mouse.x < Screen.width / 2)
{
print("Mouse is on left side of screen.");
}
if(mouse.x > Screen.width / 2)
{
print("Mouse is on right side of screen.");
}
but there is 1 problem
this code is detect the mouse if right side or left side for the Camera
but i need to detect the mouse if right side or left side for the Player,
because player can move, while camera is static [not moving with player]
Tried doing the same but with player.transform.position.x (or whatever your player object is named) ins$$anonymous$$d of Screen.width / 2?
Answer by whydoidoit · Feb 15, 2014 at 01:44 PM
You want to use Camera.WorldToScreenPoint to convert the coordinate of the player to the screen and then work out if the mouse is left or right of the player.
var playerScreenPoint = Camera.main.WorldToScreenPoint(player.transform.position);
if(mouse.x < playerScreenPoint.x) {
...
} else {
....
}
Answer by erick_weil · Feb 15, 2014 at 12:04 PM
place a plane as background to your scene, and change the name of player to player ant try out this:
mouse = Vector2(Input.mousePosition.x,Input.mousePosition.y);
var player : Vector3 = GameObject.Find("player").transform.position;
var ray : Ray;
ray = Camera.main.ScreenPointToRay(mouse);
var hit : RaycastHit;
if(Physics.Raycast(ray,hit,500))
{
//drawray only to visualize
Debug.DrawRay(Camera.main.transform.position,ray.direction*hit.distance,Color.green);
if(hit.point.x < player.x)
print("Mouse is on left side of player.");
else
print("Mouse is on right side of player.");
}
works fine . thanks but is there way without using plane as background?
why?, any collider will work, and if you disable the $$anonymous$$esh renderer in the plane you will get same results.
if have problems by the other objects in the front, if your camera is ortographic, just put the plane very very near from the camera. but if is not, I dont know how you solve this
Your answer
Follow this Question
Related Questions
Raycast Object Selection 3 Answers
Ray through camera 1 Answer
2d Position to 3d Position 2 Answers
Unity Android Movement Problem 0 Answers
Ray camera to Terrain goes Wrong. 1 Answer