- Home /
Click to Move Object till it reaches a certain place
Hi, So I have a Gameobject that I want to move slowly when I click it until it reaches a certain place, so far I got this:
using UnityEngine;
using System.Collections;
public class Moving_Planks : MonoBehaviour {
public Transform targetpos;
public float Speed = 3f;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update ()
{
}
public void MovePlanksToPlace ()
{
while( this.transform.position != targetpos.transform.position)
{
float step = Speed * Time.deltaTime;
transform.position = Vector3.MoveTowards (transform.position, targetpos.position, step);
}
}
}
But when I click it, it just moves in one step, I'd like to be slowly until it reaches the place.
I might be approaching this on the wrong side, so I'd be grateful if you could guide me to the correct path
thank you
The code works If I use it on Update() but clicking it messes the whole code up
I just tried, It just doesn't work with any mouseDown, $$anonymous$$ouseEnter or whatever at all
Please let me know if my answer helped you. If it did, I'd appreciate an accepted answer to close the question, and also boost my self esteem :)
Answer by Firedan1176 · Jul 29, 2016 at 11:26 PM
I'm sort of confused still on what you're wanting. These are the scenarios I'm picturing:
The object jumps 'increments' each time you click
The object slides 'increments' each time you click
The object slides to the target the first (and only) time you click
For the first option, you could do:
public Transform targetPos;
public int increments;
float incrementDistance;
void Start() {
incrementDistance = Vector3.Distance(transform.position, targetPos.position) / increments;
}
void Update() {
if(Input.GetMouseButtonDown(0)) JumpIncrement();
}
void JumpIncrement() {
transform.position += (transform.position - targetPos.position) * incrementDistance;
}
For the 2nd scenario you could try something like:
public Transform targetPos;
public int increments;
public float speed;
float incrementDistance;
void Start() {
incrementDistance = Vector3.Distance(transform.position, targetPos.position) / increments;
}
void Update() {
if(Input.GetMouseButtonDown(0)) JumpIncrement();
}
void JumpIncrement() {
transform.position = Vector3.Lerp(transform.position, transform.position + (transform.position - targetPos.position) * incrementDistance, speed * Time.deltaTime);
}
And the 3rd:
public Transform targetPos;
public float speed;
void Update() {
if(Input.GetMouseButtonDown(0)) GoToTarget();
}
void GoToTarget() {
transform.position = Vector3.Lerp(transform.position, targetPos.position, speed * Time.deltaTime);
}
Sorry, I get confused easily. Do any of these help you?