- Home /
Moving to mouse click, for player which floats.
Hi, i have implemented a moving to mouse click script. It works, if the player is placed on the ground. However, i have a player which is a floating spaceship in 3D space and when i click on the ground the player would not go direct to the point which the ray has hit in 3D space, but it would go to the mouse click position which was hit in 2D. In other words, it If i click on a point which is a little bit behind the player but to the left it would go only to the mouse click in 2D space but not to where the raycast hit. So in other words i want the player to go directly to where the ray hit.
private void PlayerMovement()
{
//Get the distance to the point that we have clicked at
float fDistanceToPoint = Vector3.Distance (lastPoint, objTransform.position);
//Enforce the y position of our floating player.
Vector3 pos = objTransform.position;
pos.y = 1.949471f;
objTransform.position = pos;
//Check for our mouse down. Once mouse button is down, then we check for the point where it has hit
//using a screen to point ray.
if(Input.GetMouseButtonDown(0))
{
RaycastHit hit = new RaycastHit();
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float rayDistance;
Plane aPlane = new Plane(Vector3.up, objTransform.position/5);
if(aPlane.Raycast(ray, out rayDistance))
{
Vector3 targetPoint = ray.GetPoint(rayDistance);
lastPoint = ray.GetPoint(rayDistance);
Vector3 _distance = targetPoint - transform.position;
_distance.y = 0.0f;
Quaternion lookRotation = Quaternion.LookRotation(_distance);
//lookRotation.x = 0.0f;
objTransform.rotation = lookRotation;
//objTransform.transform.LookAt(_distance);
Debug.Log (_distance);
}
}
//Change our states, depending on the distance
if(fDistanceToPoint >= 0.001f)
{
curState = PlayerStates.Moving;
}
else
{
curState = PlayerStates.Idle;
}
}
Is there any other way to get it to move to the position? My player moves to the point using :
objTransform.transform.position = Vector3.MoveTowards (objTransform.position, lastPoint, fSpeed * Time.deltaTime);
EDIT: Solved. New code has been uploaded.
Please post an answer to your own question, explaining your fix, then check your answer correct. This helps $$anonymous$$imize the amount of unanswered questions on the forum.