how to make an object move towards another in unity
/// <summary>
/// Move 2D sprite towards target
/// </summary>
/// <param name="target"></param>
/// <param name="movementSpeed"></param>
private void Move(Vector3 target, float movementSpeed)
{
//Move
transform.position += (target - transform.position).normalized * movementSpeed * Time.deltaTime;
}
4.33
6
transform.position = Vector3.MoveTowards(transform.position, taretPos, Qiaternion.identiy)
Thank you!
6
0
4
6
// the script has been edited a little but is still very similar to the original post
public float speed;
public GameObject object1; // The game object that moves.
public GameObject object2; // the game object that Object 1 moves to.
void FixedUpdate()
{
// Calculate direction vector.
Vector3 dirction = object1.transform.position - object2.transform.position;
// Normalize resultant vector to unit Vector.
dirction = -dirction.normalized;
// Move in the direction of the direction vector every frame.
object1.transform.position += dirction * Time.deltaTime * speed;
}
Thank you!
6
0
4.4
5
// 3D
transform.position = new Vector3(GameObject.Find("Object").transform.position.x, GameObject.Find("Object").transform.position.y, GameObject.Find("Object").transform.position.z);
// 2D
transform.position = new Vector2(GameObject.Find("Object").transform.position.x, GameObject.Find("Object").transform.position.y);
Thank you!
5
0
4.13
8
//This will work for 2d or 3d platforms
//Make sure to call in Update or else it wont work
Vector3.MoveTowards(transform.position, taretPos, Qiaternion.identiy)
Thank you!
8
0
4.78
9
Vector3 input = new Vector3 (Input.GetAxis("Horizontal"), 0 , Input.GetAxis("Vertical");
Vector3 dir = input.normalized;
Vecotr3 vel = dir * speed * Time.deltaTime;
transform.Translate(vel);
Thank you!
9
0
Are there any code examples left?
New code examples in category Other