The question is answered, right answer was accepted
Moving object between points
Hello, I want to make an object move from point A: Vector3(-7, 1, 153) to point B: Vector3(7, 1, 153) but i want this object to start moving from position Vector3(1, 1, 153) and then go left to A and right to B all the time.
Right now i have something like this:
public Rigidbody cube;
public float speed = 1f;
Vector3 pointA;
Vector3 pointB;
Vector3 pointC;
void Start()
{
pointA = new Vector3(1, 1, 153);
pointB = new Vector3(-7, 1, 153);
pointC = new Vector3(7, 1, 153);
}
void Update()
{
float time = Mathf.PingPong(Time.time * speed, 1);
transform.position = Vector3.Lerp(pointA, pointB, time);
}
}
but by this code my object move from starting position to the A point only and bouncing between them. How can I make it move like startingPosition>A point>B point>A point>B point etc.?
And side question, how can i change the speed of this object?
Answer by JPhilipp · Feb 13, 2020 at 12:51 PM
Note how your target vectors A, B and C are really a list, so it can be beneficial to express them as such, too. In below, we're assigning the vectors to an array, and can then use a neat targetIndex to move towards them, as well as switch to the next goal when needed.
using UnityEngine;
public class Mover : MonoBehaviour
{
const float speed = 50f;
Vector3[] targets = null;
int targetIndex = 0;
void Start()
{
targets = new Vector3[]
{
new Vector3(1f, 1f, 153f),
new Vector3(-7f, 1f, 153f),
new Vector3(7f, 1f, 153f)
};
}
void Update()
{
FollowTarget();
}
void FollowTarget()
{
Vector3 target = targets[targetIndex];
transform.position = Vector3.MoveTowards(
transform.position, target, speed * Time.deltaTime);
if (transform.position == target) { ChooseNextTarget(); }
}
void ChooseNextTarget()
{
switch (targetIndex)
{
case 0: targetIndex = 1; break;
case 1: targetIndex = 2; break;
case 2: targetIndex = 1; break;
}
}
}
Speed can be increased by increasing the speed
value at the top.
Now, it looks like you're using a rigidbody, too. If so, you normally want to try move it via either AddForce()
applied in the proper direction, or its MovePosition()
function, and for the latter, do so in a FixedUpdate()
by using time.fixedDeltaTime
. Otherwise, things like collision push forces may not be appropriately applied in the physics simulation.
Good luck!
Follow this Question
Related Questions
Increase spawn object movement when player collects every 10 points 0 Answers
How to move an object with a starting and ending speed and time 0 Answers
How can I change the design of game_object at runtime? 0 Answers
How to move an object, depend to a second 0 Answers
How can i detect a collision with many Terrains?, since my collider is not working? 0 Answers