I am trying to move my character along the X axis using my mouse cursor. I have searched around and found some scripts such as unifycommunity.com
However, these are all moving the object to the exact position of the mouse, at the moment, I have it so that it moves up when the spacebar is pressed and falls to the ground when it isn’t and i’d like to keep this for the Y axis movement, but get the object to follow my mouse’s X axis co-ordinates for the objects movement horizontally. But I can’t figure out a way to do this without the object moving to the mousePosition Y and X co-ordinates.
Here is a script re-written for your purpose. Make sure you read it, the raycast is what is doing the work , and answering your question ( as suggested by @BY0LOG1C ).
private var mouseposX : float;
private var rayHitWorldPosition : Vector3;
var yourObject : Transform;
function Update () {
if (Input.GetKeyDown(KeyCode.Mouse0))
{
// raycast
var rayHit : RaycastHit;
if(Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), rayHit))
{
// where did the raycast hit in the world - position of rayhit
rayHitWorldPosition = rayHit.point;
print ("rayHit.point : " + rayHit.point + " (rayHitWorldPosition)");
mouseposX = rayHit.point.x;
}
yourObject.position.x = mouseposX;
}
}
You’ll need to convert the mouse position from screen area to world position, using something like Camera.ScreenToWorldPoint() , this exact code is untested but I’Ve used this before IIRC:
function Update():void
{
myObject.transform.position.x = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;
}