- Home /
Gameobjects move towards a moving object c#
I'm trying to get the following gameobjects to move towards another (my player), the only problem is with the following code, they only move towards its starting position. Where as I want them to be pulled towards where ever the player currently is. Any help would be appreciated.
public Transform player;
float speed = 5.0f;
void Update () {
if (PlayerScript.pulltime > 0)
transform.position = Vector3.MoveTowards(transform.position, player.position, speed*Time.deltaTime);
}
The Players movement script is as follows:
void moveship ()
{
if (Input.GetKey (KeyCode.UpArrow))
moveshipUp ();
if (Input.GetKey (KeyCode.DownArrow))
moveshipDown ();
if (Input.GetKey (KeyCode.RightArrow))
moveshipLeft ();
if (Input.GetKey (KeyCode.LeftArrow))
moveshipRight ();
}
void moveshipUp ()
{
if (this.transform.position.y < 3.4) {
this.transform.Translate (Vector3.up * speed * Time.deltaTime, Space.World);
}
}
void moveshipDown ()
{
if (this.transform.position.y > -4.388) {
this.transform.Translate (Vector3.down * speed * Time.deltaTime, Space.World);
}
}
void moveshipLeft ()
{
if (this.transform.position.x < 8.23) {
this.transform.Translate (Vector3.right * speed * Time.deltaTime, Space.World);
}
}
void moveshipRight ()
{
if (this.transform.position.x > -8.284) {
this.transform.Translate (-Vector3.right * speed * Time.deltaTime, Space.World);
}
}
It should be following it's updated movement, but it doesn't.
Answer by MagicoCreator · Jan 27, 2014 at 08:44 PM
try setting player as a GameObject and access it's position by player.transform.position
well i just tried your script and it works as it is by me, so the modification i proposed is totally useless, it is tracking current position and moving towards correctly, if it doesn't work you are maybe setting the transform wrong i.e. instanciating a transform value yourself and filling it with static values, or that your player moves by animation whose movement isn't baked into the pose, and the original position of your character doesn't change
I've added the player movement script above. Sorry to keep asking, but do you see anything there which could be causing this? The Player is just a prefab with the movement script attached.
the movement script moves the transform so it shouldn't be a problem, unless your ship is parented to the player object and, you target your main object into the other object's script which doesn't move
Hmmm no it's just a single prefab, no children or parenting. :/