move towards unity code example
Example 1: move towards target unity
private void Move(Vector3 target, float movementSpeed)
{
transform.position += (target - transform.position).normalized * movementSpeed * Time.deltaTime;
}
Example 2: unity go towards
transform.position = Vector3.MoveTowards(transform.position, target.position, speed);
To better understand :
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour
{
public float speed = 1.0f;
private Transform target;
void Awake()
{
transform.position = new Vector3(0.0f, 0.0f, 0.0f);
GameObject cylinder = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
Camera.main.transform.position = new Vector3(0.85f, 1.0f, -3.0f);
target = cylinder.transform;
target.transform.localScale = new Vector3(0.15f, 1.0f, 0.15f);
target.transform.position = new Vector3(0.8f, 0.0f, 0.8f);
Camera.main.transform.position = new Vector3(0.85f, 1.0f, -3.0f);
Camera.main.transform.localEulerAngles = new Vector3(15.0f, -20.0f, -0.5f);
GameObject floor = GameObject.CreatePrimitive(PrimitiveType.Plane);
floor.transform.position = new Vector3(0.0f, -1.0f, 0.0f);
}
void Update()
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
if (Vector3.Distance(transform.position, target.position) < 0.001f)
{
target.position *= -1.0f;
}
}
}
Example 3: how to make an object move in unity
Vector3 input = new Vector3 (Input.GetAxis("Horizontal"), 0 , Input.GetAxis("Vertical");
Vector3 dir = input.normalized;
Vecotr3 vel = dir * speed * Time.deltaTime;
transform.Translate(vel);
Example 4: movetowards unity
void Update()
{
transform.position += (target - transform.position).normalized * movementSpeed * Time.deltaTime;
}
Example 5: how to move towards an object unity
Vector3.MoveTowards(transform.position, taretPos, Qiaternion.identiy)