I am currently using mouse inputs to move a player (sphere) in a 3d world. I am doing this with a raycast and using the hit.point
coordinates. This is the way I want my game to work, but it is a 3d game, so whenever I move the player, using the mouse coordinates, it won't align properly. This is due to the player being 3d and the mouse coordinates being 2d.
Here is my code:
public float speed;
public GameObject player;
private Ray ray;
private RaycastHit hit;
private Vector3 mousePos;
void Start ()
{
}
void FixedUpdate ()
{
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hit))
{
mousePos = new Vector3(hit.point.x, /*Insert Code*/, hit.point.z);
if(mousePos != player.transform.position)
{
player.transform.position = Vector3.MoveTowards(player.transform.position, mousePos, speed * Time.deltaTime);
}
}
}
My question is this:
If I have the player at 1.3f above the ground, how can I manipulate Vector3.MoveTowards
so the mouse is centered in the player without affecting the height of the player (1.3f)?
I tried using player.transform.position.y
, but it placed the mouse directly under the player (the x and z values worked, but the y-value didn't).
I, also, tried hit.point.y, but it gave me values greater than the player height (1.3f).
This might not be the best way to solve my issue but it solves it for now. I made a plane with a y value of 1.3f and put it through the player object. I, then, made the object invisible. Now, the raycast will hit that object instead of the ground.