- Home /
Mouse movement object in a straight line
I have this project where I'm hammering nails into a board and control the hammers location by having it follow the mouse position. It's currently pivoting in an arc around the camera at a distance of 22. How could I make it so it just move in a straight line across the screen instead of arcing around the camera?
using UnityEngine; using System.Collections;
public class HammerMovement : MonoBehaviour {
private float distance = 22f;
private Transform hammer;
void Start()
{
hammer = GetComponent<Transform>();
Cursor.visible = false;
}
void Update()
{
MoveHammer();
}
void MoveHammer()
{
Vector3 pos = Input.mousePosition;
Ray ray = Camera.main.ScreenPointToRay(pos);
Vector3 point = ray.origin + (ray.direction * distance);
hammer.position = point;
}
You only need the local z Axis be in a fixed distance. Try:
void $$anonymous$$oveHammer()
{
Vector3 pos = Input.mousePosition;
Ray ray = Camera.main.ScreenPointToRay(pos);
Vector3 point = ray.origin + (ray.direction * distance);
hammer.position = point;
Vecto3 pos=hammer.localPosition;
pos.z=22;
hammer.localPosition= pos;
}
Answer by Zayn-SIddiqui · Oct 08, 2016 at 05:08 PM
This is headed in the right direction, but is the second Vector3 pos, supposed to be a new variable? I already defined a vector3 named "pos" at the start of the function so I get an error when this code is added. I tried just changing the variable name but that didn't change anything.
Answer by Zayn-SIddiqui · Oct 08, 2016 at 05:08 PM
This is headed in the right direction, but is the second Vector3 pos, supposed to be a new variable? I already defined a vector3 named "pos" at the start of the function so I get an error when this code is added. I tried just changing the variable name but that didn't change anything.