- Home /
Mouse Follow Controller
Hi all! I'm making a small independent game where I want less buttons and controls than your average game,using only the mouse and space button,but twice the Fun! :) But I have a problem. The player will be a simple ball in 3D space with a Rigidbody(3/4 top down veiw game), and the ball must follow the mouse within a certain distance. I might need variables to experiment. Usually, I write my own scripts, because I have some clue on how to start. But this one is no exception. I have absolutely no idea. If you can provide a script for me, that be awesome. Thanks!
Answer by Jayland · Aug 06, 2011 at 07:22 PM
BTW, I don't want it to be clicking, Just follow the mouse without clicking.
Answer by aldonaletto · Aug 06, 2011 at 10:59 PM
You must cast a ray at Update and translate the object to the hit point - if any. This script was intended to run in the XZ plane, and the object must have a rigidbody with Use Gravity checked.
var speed: float = 2; var maxSpeed: float = 20; private var dest: Vector3;
function Start(){ dest = transform.position; }
function Update(){ var ray = Camera.main.ScreenPointToRay(Input.mousePosition); var hit: RaycastHit; if (Physics.Raycast(ray, hit)){ // if mouse pointer hit dest = hit.point; // some update destination } var mov = dest - transform.position; // find direction to move mov.y = 0; // zero y to do not interfere with gravity mov = mov speed; // apply speed if (mov.magnitude > maxSpeed){ // clamp speed to maxSpeed mov = mov.normalized maxSpeed; } // move in horizontal direction transform.Translate(mov * Time.deltaTime, Space.World); }
Your answer
![](https://koobas.hobune.stream/wayback/20220612171851im_/https://answers.unity.com/themes/thub/images/avi.jpg)