Hi again =D
Now that I got my last problem solved, I’m trying to do a point-and-click feature that moves an object left or right to wherever the mouse clicked on the x axis.
I’ve been looking around but most threads are to do with Diablo style movement, 3D space movement etc.
I just want an object to move left or right on the x axis and only move towards the point where the mouse has clicked on the x axis.
Can anyone help me? I’m thinking that to do this, I would have to point and click and then a script goes “if object.x < mouse.x then move object right else move left”. Is that the right logic?
Yea, that’s the right basic logic. From there, it’s refinement. Consider adding a speed variable that controls how fast the avatar moves to the desired point. Then make sure it doesn’t overshoot and stays still when it reaches its destination.
Cool, at least my thinking was right.
I’m currently playing around and can’t seem to get things working. This is what i got so far:
{
//Mouse click to move character
var mouseClick : Vector3 = Input.mousePosition;
var mouseClickPos : Vector3;
var mouseClickToggle : int = 0;
var moveDir : int = 0;
if (Input.GetMouseButton(0))//Input.GetKey(KeyCode.Mouse0) mouseClickToggle == 0)
{
//mouseClickPos = mouseClick;
mouseClickpos = Input.mousePosition;
mouseClickToggle = 1;
Debug.Log("CLICKED!");
}
if (mouseClickPos.x < 0)
{
moveDir = -1;
Debug.Log("LEFT");
}
else
{
moveDir = 1;
Debug.Log("RIGHT");
}
if (!Input.GetKey(KeyCode.Mouse0))
{
mouseClickToggle = 0;
}
var horizontalMovement = moveDir * speed * Time.deltaTime;
var newPos = rigidbody.position + Vector3(horizontalMovement, 0, 0);
rigidbody.MovePosition(newPos);
The above script is placed in the actual character object/prefab.
I assume this code is inside the Update function, though the target positions should be stored outside of it.
You probably want to use GetMouseButtonDown instead of GetMouseButton, but it’ll work either way.
The mouse position is in screen space, not 3D space. You need to convert it somehow, depending on how you set up the camera. Camera.main.ScreenToWorldPoint(Input.mousePosition) will do the trick with an orthographic camera.
You should compare the target position with the character’s current position, not zero, as movement goes from character position towards target position.
Then you actually have to move the character.