MoveTowards not moving accurately. Getting stuck on target.
So I've got the MoveTowards working in a way that was unexpected. If I drive the player all the way to the targetThingy then the reverse MoveTowards stops working, effectively trapping me right next to the target. If I keep away from the target its fine and I can move backwards.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour {
public GameObject targetThingy;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
float step = 3 * Time.deltaTime;
if (Input.GetKey(KeyCode.A))
{
transform.RotateAround(targetThingy.transform.position, new Vector3(0, 0, 1), 200 * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D))
{
transform.RotateAround(targetThingy.transform.position, new Vector3(0, 0, -1), 200 * Time.deltaTime);
}
if (Input.GetKey(KeyCode.W))
{
transform.position = Vector2.MoveTowards(transform.position,targetThingy.transform.position, step);
}
if (Input.GetKey(KeyCode.S))
{
transform.position = Vector2.MoveTowards(transform.position, targetThingy.transform.position, -step);
}
}
}
Answer by qwertyjulz · Sep 10, 2018 at 08:20 AM
Okay, so I figured it out.
If the player moves to a position that is identical with the targets position then the MoveTowards function stops being being effective because of the the fact that the calculation its running essentially loses a variable;
The "distance between" becomes zero and if the two variable positions are THE SAME position then how can the MoveTowards function work?
So the solution I used was to put a box collider on both game objects, effectively preventing them from ever sharing the same transform position.
Answer by Bunny83 · Sep 11, 2018 at 06:27 AM
Sorry but you're using MoveTowards in a completely strange and unintended wrong way. As the name says the method moves towards a target point. You basically use it to "move away" from the target which makes not much sense. It kind of works as long as you have some distance from the "target" since this defines a direction. However if you are already at the target position there is no direction.
Look at your left / right case. You actually use two different target positions and you always use a positive delta which is the correct way to use this method.
It generally seems a bit strange to use MoveTowards for a character control script. How does your scene setup looks like?
Your answer
Follow this Question
Related Questions
How To Do Basic 2D Movement? 1 Answer
Sprite not moving properly? 0 Answers
Help with Vector3.Distance 0 Answers
How can I make smooth steps around an object? 0 Answers
Move Player along normal of floor? 1 Answer