- Home /
How do I go about moving an object side to side using the mouse.
So basically I have an object in front of the camera and I want the player to be able to move it side to side when holding down a mouse button and dragging. Here is what I have so far. The object does not move at all.
public bool is_handling;
public Vector3 mouseReference;
public Vector3 mouseOffset;
public Vector3 stickPos;
private float sensitivity;
public void Start() {
stickPos = Vector3.zero;
sensitivity = 0.4f;
}
public void Update() {
if(Input.GetMouseButton(1)){
is_handling = true;
mouseReference = Input.mousePosition;
print (mouseReference);
} else {
is_handling = false;
}
if(is_handling) {
print(Input.mousePosition);
mouseOffset = (Input.mousePosition - mouseReference);
print (mouseOffset);
stickPos.x = (mouseOffset.x) * sensitivity;
transform.Translate(stickPos);
mouseReference = Input.mousePosition;
}
}
}
Did you want to move when you hold right click? Because left click is mouse button 0 right click is mouse button 1.
Answer by RobAnthem · Dec 09, 2016 at 06:19 AM
Assuming you actually want this to move in 3-Dimensional space, a simple mouse vector wont translate into the world, so you'll need to raycast. Assuming you want your raycast to pertain to the terrain, this is sort of what you want. If you want an actual raycast that hits anything, it is a little different, but essentially you need a raycast. The mousePosition only applies to 2D space, and must be raycast through the camera.
void Update() {
if (Input.GetMouseButtonDown (1)) {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (goTerrain.GetComponent<Collider>().Raycast (ray, out hit, Mathf.Infinity)) {
transform.position = hit.point;
}
}
}
}
Answer by getyour411 · Dec 09, 2016 at 04:12 AM
18 sets mouseRef = Input.mousePos; 28 substracts Input.mousePos from mouseRef(Input.mousePos) so 0.
I believe Input.mousePos uses a different coordinate system so you probably need a Camera.main.ScreentoWorldPoint conversion
Your answer
Follow this Question
Related Questions
Mirroring Object Movement with Mouse Position 2 Answers
Move an object to mousePosition 2 Answers
Can someone explain why my Raycasting doesn't work? please :) 2 Answers
Rotation with mouse instantly resets 1 Answer
2D get touch input 1 Answer