Legacy Documentation: Version 4.5.0

Script language:

  • JS
  • C#
  • Boo
Script language

Select your preferred scripting language. All code snippets will be displayed in this language.

Vector3.RotateTowards

static function RotateTowards(current: Vector3, target: Vector3, maxRadiansDelta: float, maxMagnitudeDelta: float): Vector3;
static Vector3 RotateTowards(Vector3 current, Vector3 target, float maxRadiansDelta, float maxMagnitudeDelta);
static def RotateTowards(current as Vector3, target as Vector3, maxRadiansDelta as float, maxMagnitudeDelta as float) as Vector3

Description

Rotates a vector current towards target.

This function is similar to MoveTowards except that the vector is treated as a direction rather than a position. The current vector will be rotated round toward the target direction by an angle of maxRadiansDelta, although it will land exactly on the target rather than overshoot. If the magnitudes of current and target are different then the magnitude of the result will be linearly interpolated during the rotation. If a negative value is used for maxRadiansDelta, the vector will rotate away from target/ until it is pointing in exactly the opposite direction, then stop.

	// The target marker.
	var target: Transform;
	
	// Angular speed in radians per sec.
	var speed: float;
	
	function Update () {
		var targetDir = target.position - transform.position;
		
	    // The step size is equal to speed times frame time.
	    var step = speed * Time.deltaTime;
	    
	    var newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0);
	    Debug.DrawRay(transform.position, newDir, Color.red);
	    // Move our position a step closer to the target.
	    transform.rotation = Quaternion.LookRotation(newDir);
	}
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public Transform target;
    public float speed;
    void Update() {
        Vector3 targetDir = target.position - transform.position;
        float step = speed * Time.deltaTime;
        Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0F);
        Debug.DrawRay(transform.position, newDir, Color.red);
        transform.rotation = Quaternion.LookRotation(newDir);
    }
}
import UnityEngine
import System.Collections

public class ExampleClass(MonoBehaviour):

	public target as Transform

	public speed as float

	def Update() as void:
		targetDir as Vector3 = (target.position - transform.position)
		step as float = (speed * Time.deltaTime)
		newDir as Vector3 = Vector3.RotateTowards(transform.forward, targetDir, step, 0.0F)
		Debug.DrawRay(transform.position, newDir, Color.red)
		transform.rotation = Quaternion.LookRotation(newDir)