- Home /
moving towards mouse position
Hi there, My game is using top down orthographic.. by holding the mouse button the player object moves towards the mouse position... Using Raycast i was able to successfully detect target location using the mouse position and able to move the character there, however, my character drifts upwards along the Y axis.. ive spent days googling and trying different methods and im sure it has something to do with the way the camera (ScreenPointToRay) calculates its own transform in 3D space.. please correct me if im wrong, but can someone also point me in the right direction ? thanks in advance :)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Controller : MonoBehaviour
{
public Transform moveThis;
public float speed = 10f;
public LayerMask hitLayers;
void Update ()
{
Vector3 mouse = Input.mousePosition;
Ray castPoint = Camera.main.ScreenPointToRay (mouse);
RaycastHit hit;
if (Input.GetMouseButton(0))
{
if (Physics.Raycast (castPoint, out hit, Mathf.Infinity, hitLayers))
{
Vector3 moveTo = new Vector3 (hit.point.x, hit.point.y + 3, hit.point.z);
moveThis.transform.position = Vector3.MoveTowards (moveThis.transform.position, moveTo, speed * Time.deltaTime);
}
}
}
}
So is your game 2D in a sense that you're looking at it from the side? Could you post some pics so we can get a better sense of what you are trying to accomplish?
lol theres always something i forget to mention.. sorry ... its 3D.. pics wont help much.. all i have at the moment is a cube on a plane.. with a camera looking down at the plane (90 degree rotation).. ie top down orthographic view ... im trying to move the cube (player object) to where the raycast hits the plane from the mouse position
I believe you can just get the x and y cords of the mouse and move the cube there...
Answer by HarshadK · Aug 01, 2017 at 02:22 PM
In calculating the move position:
Vector3 moveTo = new Vector3 (hit.point.x, hit.point.y + 3, hit.point.z);
you are adding 3 to the y value of hit which is causing your object to elevate from the ground considering your object has size less than 6 units considering the pivot of your object is at its center.
You can use renderer.bounds.extents.y
to get the height value to add to your object's moveTo position. Something like:
Vector3 moveTo = new Vector3 (hit.point.x, hit.point.y + moveThis.GetComponent<Renderer>().bounds.extents.y, hit.point.z);