- Home /
Question by
fathantara · Jan 31, 2017 at 08:30 PM ·
following
hey guys i just wanna make simple script that an object will follow point using point's position of x and z, but when i try to play it its gonna to wrong direction not to the point.
void Start () {
float xpoint = point.transform.position.x;
float zpoint = point.transform.position.z;
float xme = this.transform.position.x;
float zme = this.transform.position.z;
Debug.Log(" point x: " + xpoint + " point z: " + zpoint + " me x: " + xme + " me z: " + zme);
}
// Update is called once per frame
void Update () {
if (xme <= xpoint)
vectorx = 1 * speed;
if (xme >= xpoint)
vectorx = -1 * speed;
if (zme <= zpoint)
vectorz = 1 * speed;
if (zme >= zpoint)
vectorz = -1 * speed;
}
void FixedUpdate()
{
if (xme != xpoint)
Debug.Log("hey pewds");
transform.position += new Vector3(vectorx * Time.deltaTime, 0f, 0f);
if (zme != zpoint)
transform.position += new Vector3(0f, 0f, vectorz * Time.deltaTime);
}
}
Comment
Answer by destructivArts · Jan 31, 2017 at 11:48 PM
It would be faster, and more reliable to do something like this:
public Vector3 TargetPoint;
public float Speed;
public float TargetDistance;
private Vector3 m_MoveDirection;
void Start () {
m_MoveDirection = TargetPoint - transform.position;
m_MoveDirection.Normalize();
}
void Update () {
float CurrentDistance = Vector3.Distance (TargetPoint, transform.position);
// If moving full speed for one frame would have the object overshoot, just move to the target
if (CurrentDistance < Speed * Time.deltaTime) {
transform.position = TargetPosition;
// If we are further than our minimum distance to the target, move full speed towards it
} else if (CurrentDistance > TargetDistance) {
transform.Translate (m_MoveDirection * Speed * Time.deltaTime);
}
}
Your answer
Follow this Question
Related Questions
Help me: Wasd movement, Model following my mouse 0 Answers
Make an enemy follow a player through network 4 Answers
Having a goalie follow the ball but not move towards it 2 Answers
Object following List of Vector3 coordinates 1 Answer
Make object go back to original spawn distance (Similar to Rust building system) 1 Answer