Skip to content

Instantly share code, notes, and snippets.

@kurone-kito
Last active January 20, 2019 09:48
Show Gist options
  • Save kurone-kito/6bea2255df48bd70d9fb33199a685226 to your computer and use it in GitHub Desktop.
Save kurone-kito/6bea2255df48bd70d9fb33199a685226 to your computer and use it in GitHub Desktop.
A behavior script for Unity: for moving an object in a rect shape by turning it at a right angle using a quaternion when outed a certain range.
using UnityEngine;
public class CubeBehavior : MonoBehaviour
{
const float threshold = 1f;
private readonly Quaternion quaternion = Quaternion.AngleAxis(90, Vector3.down);
public Vector3 direction = Vector3.forward * 0.1f;
// Update is called once per frame
void Update()
{
var previous = transform.position;
var next = previous + direction;
if (Mathf.Max(Mathf.Abs(next.x), Mathf.Abs(next.z)) >= threshold)
{
direction = quaternion * direction;
}
else {
transform.position = next;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment