Vector3.MoveTowards
Hi
I am currently trying to work out how to move an object (player) to another object once a mouse button has been clicked.
Moving the player using the following script works when no mouse click detect is required.
using UnityEngine;
using System.Collections;
public class MoveToTarget : MonoBehaviour
{
public Transform target;
public float speed;
void Update()
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards (transform.position, target.position, step);
}
}
However when I add detecting mouse-click the player does move in the direction of the object but stops, waiting for another click before it moves again.
using UnityEngine;
using System.Collections;
public class MoveToTarget : MonoBehaviour
{
public Transform target;
public float speed;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards (transform.position, target.position, step);
}
}
}
Should I be using something other than void update?
Can someone point me in the right direction with regards to seeing what options are available other than void update?
Thanks
Answer by Landern · Nov 24, 2015 at 03:09 PM
Try using GetMouseButton which returns true for a given button being held down, GetMouseButtonDown only returns true during a frame and the button is pressed.
Answer by Nano-Additcs · Nov 24, 2015 at 11:53 PM
Cool, thanks. Good to know yet another trick :) When I hold the button down it does indeed move the player to the target's position. However to clarify (my apologies for not doing so previously) I would like to click and release the mouse button once and have the player travel to its new location. Currently if I release the mouse button the player stops. Thanks
DERP!
Like a Newbie I completely missed simply increasing the speed value in order to get the desired effect...
Although it doesn't move it to the target position in slow mo if desired. It'll do until the whisky wears off and clarity returns