- Home /
Mouse move with specific speed?
How can i make my sphere continuously following the mouse but always with the same speed? Also if the mouse moves faster than the speed of the sphere.
this is just the follow script without a specific speed for the sphere.
#pragma strict
var depth = 10.0;
function Start ()
{
Screen.showCursor = false;
}
function Update ()
{
var mousePos = Input.mousePosition;
var wantedPos = Camera.main.ScreenToWorldPoint (Vector3 (mousePos.x, mousePos.y, depth));
transform.position = wantedPos;
}
Thanks for your help!!
Answer by robertbu · May 03, 2014 at 07:26 PM
Add a speed variable and change line 14 to get the following script:
#pragma strict
var depth = 10.0;
var speed = 1.5;
function Start ()
{
Screen.showCursor = false;
}
function Update ()
{
var mousePos = Input.mousePosition;
var wantedPos = Camera.main.ScreenToWorldPoint (Vector3 (mousePos.x, mousePos.y, depth));
transform.position = Vector3.MoveTowards(transform.position, wantedPos, speed * Time.deltaTime);
}
Answer by impdesign · Sep 17, 2016 at 04:27 PM
I was brought to this forum for my Unity 2D project and am posting my solution for those other poor souls.
//Get the mouse
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos = new Vector3(mousePos.x, mousePos.y, 0);
//Rotate the sprite to the mouse point
Vector3 diff = mousePos - transform.position;
diff.Normalize();
float rot_z = Mathf.Atan2(diff.y, diff.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rot_z - 90);
//Move the sprite towards the mouse
transform.position += transform.up * speed * Time.deltaTime;
Your answer
Follow this Question
Related Questions
Maximum speed mouse follow without rotation 0 Answers
Prevents a mouse click on interface to trigger a click to move script 1 Answer
Move on mouse click in Orthografic 30x45x0 angle 0 Answers
Problem with Alt + Middle Click Drag for Camera (Windows) 3 Answers
Continually Updating position of Instantiated Object (to Mouse Pointer) 0 Answers