- Home /
Question by
Gabrielexxxx · Jun 18, 2017 at 07:26 PM ·
movementinputframe
How to make a object go and come back with a mouse click
Any idea how do I move an object into point A and after a time he comes back to his original position with a mouse click ,i guess its MoveTowards but when i have no idea how to do that with a timer, and when i click with the mouse the position just go for a frame forward. :c
Comment
Answer by JxWolfe · Jun 18, 2017 at 07:32 PM
This code will move to an object then come back and go and back so on, you would have to edit it but it goes between two objects. It has a move speed, not a timer... set the move speed for the time you want...
using UnityEngine;
using System.Collections;
public class Move_Opstacle : MonoBehaviour {
public float move_speed;
public GameObject target;
public GameObject back;
GameObject targetSupostTo;
void Start()
{
targetSupostTo = target;
InvokeRepeating ("MoveTowardsTarget", 0,0.01f);
}
//move towards a target at a set speed.
private void MoveTowardsTarget() {
//the speed, in units per second, we want to move towards the target
float speed = move_speed;
//move towards the center of the world (or where ever you like)
Vector3 targetPosition = target.transform.position;
Vector3 currentPosition = this.transform.position;
//first, check to see if we're close enough to the target
if (Vector3.Distance (currentPosition, targetPosition) > .1f) {
Vector3 directionOfTravel = targetPosition - currentPosition;
//now normalize the direction, since we only want the direction information
directionOfTravel.Normalize ();
//scale the movement on each axis by the directionOfTravel vector components
this.transform.Translate (
(directionOfTravel.x * speed * Time.deltaTime),
(directionOfTravel.y * speed * Time.deltaTime),
(directionOfTravel.z * speed * Time.deltaTime),
Space.World);
} else
{ //closer then .1
if (targetPosition != targetSupostTo.transform.position) {//change to targetSupostTo
//print("targetPosition != targetSupostTo.transform.position");
target = targetSupostTo;
} else {//change to back
//print("targetPosition == targetSupostTo.transform.position");
target = back;
}
}
}
}