- Home /
Move a sprite a specific distance towards a mouse click
Hello everybody,
I already have some code working that moves a sprite towards a mouseclick on the screen in a top down game.
I would also like the ability for the object to "jump" in that direction at a faster speed, but only for a set distance (and be unable to change course during the jumping state).
if ( (Input.GetMouseButtonDown(0) || Input.GetMouseButton(0)) && isJumping == false ) {
target = Input.mousePosition;
target.z = transform.position.z - Camera.main.transform.position.z;
//convert to world coordinates
target = Camera.main.ScreenToWorldPoint(target);
}
//move towards target position in world selected by mouse
transform.position = Vector3.MoveTowards(transform.position, target, movementSpeed * Time.deltaTime);
So that all works fine, but as I say when the player presses spacebar I want the object to leap in the direction of the mouse cursor for a set distance of say 10 units and be unable to change direction until it reaches the point of landing.
I'm not using physics or gravity, I'd like it all done on distance if possible. I started looking at raycasting but was unsure if that was the right course to take?
Many thanks!
Answer by equus_ligneus · Apr 12, 2015 at 02:27 PM
You can save the point you want to leap to.
if(!isJumping)
{
// start leaping
if(Input.GetKeyDown(KeyCode.Space))
{
// the direction to leap towards
Vector3 direction = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
// do not want to move out of 2D plane
direction.z = 0;
// do not want division by zero when normalizing Vector
if(direction.sqrMagnitude < 0.001f)
{
return;
}
// Set length of direction to 1
direction = direction.normalized;
target = transform.position + direction * leapDistance;
isJumping = true;
}
else if (Input.GetMouseButtonDown(0) || Input.GetMouseButton(0)) // normal movement
{
// your code
}
}
else // leap
{
transform.position = Vector3.MoveTowards(transform.position, target, leapSpeed * Time.deltaTime);
// end leap if there
if(Vector3.sqrMagnitude(target - transform.position) < 0.01f)
{
transform.position = target;
isJumping = false;
}
}
You have to add leapDistance and leapSpeed to your code for this to work
Thank you very much for this, I was really pulling my hair out over this problem. In the end I just ended up doing it by time (ie working out how far to jump by using the speed and length of time of the jump) but I still had the problem of the target changing if you move the mouse around. I haven't tried this code yet but it looks great so thanks again!
Update: Yep code works great, very happy :)