- Home /
When an object travels a certain amount, it comes back to it's origin position
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);
}
}
Well yes, in the startfunction you're using physics (which computes displacement and changes the transform position), where as in the update you manually set the transform's position... So in the end... you just get your manual setting of the transform's position at every frame...
I guess I just don't get what that user position code is doing there... that or I didn't get what you were trying to do.. :)
Answer by hexagonius · Feb 11, 2015 at 06:15 PM
Your if in Update() will most likely always be true:
if (transform.position.x - player.transform.position.x != 0f)
Instead you could save the projectiles starting position in Start() and do a "Vector3.Distance > something" in Update. If "that's" true, either start a Coroutine to move back, or toggle a boolean that distinguishes between still being physically on the way as it was or traveling back with your MoveTowards. Set the rigidbody to isKinematic for this if you want to reliably change its position. Otherwise you're screwing with the physics engine.
Your answer
Follow this Question
Related Questions
swapping out an object on collision 2 Answers
2.5D Side-scroller Mouse Drag Objects 1 Answer
Dense joid joining! Help 0 Answers
Collision with a coin 0 Answers
Object movement impacted by another 1 Answer