Vector2 MoveTowards weird behaviour?
Im trying to do a simple platform that pushes the player if he stays inside the trigger for 10 seconds. The problem is when the platform starts moving to push the player, it moves only about 0.07 units and then starts to flicker back and forth (about 0.005 units, almost unnoticeable), stuck, unable to reach the "endPosition" I declared. There is no collider blocking the way. Script:
private float timer;
private GameObject pusherPlatform;
private Transform endTransform;
private Vector2 restPos;
private Vector2 endPos;
void Start() {
pusherPlatform = this.gameObject.transform.GetChild(0).gameObject;
endTransform = transform.GetChild(1);
restPos = pusherPlatform.transform.localPosition;
endPos = endTransform.localPosition;
print(restPos);
print(endPos);
}
private void OnTriggerStay2D(Collider2D col) {
if (col.gameObject.tag == "PlayerOne" || col.gameObject.tag == "PlayerTwo") {
timer += Time.deltaTime;
}
}
private void OnTriggerExit2D(Collider2D colExit) {
if (colExit.gameObject.tag == "PlayerOne" || colExit.gameObject.tag == "PlayerTwo") {
timer = 0;
}
}
void Update() {
if (timer >= 10) {
ActivatePush();
}
}
void ActivatePush() {
pusherPlatform.transform.localPosition = Vector2.MoveTowards(restPos, endPos, 10 * Time.deltaTime);
}
}
For debugging, printing the restPos and endPos, both are on point, exactly where they should be, Thanks in advance :)
The moveTowards line is wrong. Your current position isn't an input, so there's no way it can possibly move closer from where you are now. Look at examples of moveTowards - the first input is usually your current position.
You are right, as the restPos stored position is the same as the transform.localposition in the start, I thought I would have no problems, but welp. Thanks :)
Answer by UnityCoach · Oct 24, 2018 at 10:11 PM
10 * Time.deltaTime
means the object will move 10 units per second at the fastest.
You have a lot of unnecessary accesses, which make things hard to read.
private GameObject pusherPlatform;
pusherPlatform = this.gameObject.transform.GetChild(0).gameObject;
You don't seem to use pusherPlatform for anything but its Transform. You can reference a Transform instead. this
is implicit, and so is gameObject
. In other words, you can do this :
private Transform pusherPlatform;
pusherPlatform = transform.GetChild(0);
restPos = pusherPlatform.localPosition;
@Owen-Reynolds is right about MoveTowards, you usually make it move from your current position. Like this :
pusherPlatform.transform.localPosition = Vector2.MoveTowards(pusherPlatform.transform.localPosition, endPos, 10 * Time.deltaTime);
Or, you use Vector2.Lerp (restPos, endPos, delta)
.
float pushSpeed = 1; // in seconds
float pushValue = 0;
void ActivatePush()
{
pushValue += Time.deltaTime / pushSpeed;
pusherPlatform.transform.localPosition = Vector2.Lerp(restPos, endPos, pushValue);
}
Hope this helps you figure this out.