- Home /
Question by
kmetcalfe1 · Sep 20, 2019 at 02:02 PM ·
mousemousepositionbounds
Child item on moving and rotating character follows mouse within bounds
I have a character with antennae, and his antennae tips (small spheres) should follow the on-screen mouse within a certain bounds (I try (1,1,1) here). The tips should smoothly move toward the mouse and stop moving at the bounds, and continue moving again if the mouse pointer becomes in-bounds or moving toward the mouse is an in-bounds direction. Current code:
public class antennaeTops : MonoBehaviour
{
Vector3 lastPos;
float distanceFromCamera;
Vector3 boundVector = new Vector3(1, 1, 1);
void Start()
{
distanceFromCamera = Vector3.Distance(transform.position, Camera.main.transform.position);
}
void FixedUpdate()
{
Vector3 pos = Input.mousePosition;
pos.z = distanceFromCamera;
pos = Camera.main.ScreenToWorldPoint(pos);
if ((pos-transform.position).magnitude <= boundVector.magnitude)
{
transform.position = Vector3.MoveTowards(transform.position, pos, 2f*Time.deltaTime);
pos.z = distanceFromCamera;
}
}
}
Basically, I try to get the distance from the antennae tops to the camera (also a child of the character) and hold that z position as the x and y position move according to where the mouse is. The tips seem to stop in random points and not stay within any kind of bounds. Help!
Comment