I have a shot prefab, I want it to travel some distance after it was created and if it reaches a certain distance it comes back to it’s original position, I have played around with the code but I couldn’t get it to work.
The stuff in start should determine that when the object is created it travels at that speed in the direction, but the code in the update function stops it from doing that and at object creation it starts to move it to the player position.
How to fix that?
using UnityEngine;
using System.Collections;
public class movement : MonoBehaviour {
public float boostSpeed;
private GameObject player;
public float speed;
// Use this for initialization
void Start () {
player = GameObject.FindGameObjectWithTag("Player");
if(player.transform.localScale.x == -1){
rigidbody2D.AddForce(transform.right * (boostSpeed * -1f) );
}
else{
rigidbody2D.AddForce(transform.right * boostSpeed);
}
}
// Update is called once per frame
void Update () {
boostSpeed = 1f * 5f;
float distance = Vector3.Distance(player.transform.position, transform.position);
float step = speed * Time.deltaTime;
if(transform.position.x - player.transform.position.x != 0f){
transform.position = Vector3.MoveTowards(transform.position, player.transform.position, step);
}
}