- Home /
Question by
Javyer · Jun 01, 2015 at 11:54 PM ·
objectnewbiemovetowards
Make object move towards position without stopping
Hello! I want to make the objects from Roll-A-Ball tutorial to move towards the direction of the player when they spawn, but my problem is that when they move to the last position, they stop there, I want them to continue once they start moving. How can I solve this?
Here is my code:
public class Rotator : MonoBehaviour {
private GameObject mytarget;
private Transform targetPos;
public float mySpeed;
private Vector3 playerPos;
public float speed;
void Start () {
mytarget = GameObject.FindGameObjectWithTag("Player");
playerPos = mytarget.transform.position;
mySpeed = 2;
}
void Update () {
transform.Rotate (new Vector3 (15, 30, 45) * Time.deltaTime);
var step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, playerPos, step);
}
}
Thanks to whoever helps me!
Comment
Answer by YoungDeveloper · Jun 01, 2015 at 11:59 PM
Because you save the starting player position in a Vector3, which is a copy of those values and is not updated. Note that you will also have to fix the targets y before applying.
private Transform target;
private float speed = 2f;
private Vector3 speedRot = Vector3.right * 50f;
void Start () {
target = GameObject.FindGameObjectWithTag("Player").transform;
}
void Update () {
transform.Rotate (speedRot * Time.deltaTime);
transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
That would make the object move toward the player position all the time, I'm trying to make it move in the direction the player was when the object spawned.
Create states or enable/disable the script.
private enum STATE{
$$anonymous$$OVE,
IDLE
}
private STATE state = STAT$$anonymous$$$$anonymous$$OVE;
private void setState(STATE state){
this.state = state;
}
private void Update(){
if(state == STAT$$anonymous$$$$anonymous$$OVE){
transform.Rotate (speedRot * Time.deltaTime);
transform.position = Vector3.$$anonymous$$oveTowards(transform.position, target.position, speed * Time.deltaTime);
if(transform.position == target.position){
setState(STAT$$anonymous$$IDLE);
}
}
}