I'm working on a 3D game in Unity that requires lock-on, or Z, targeting found in games like Dark Souls and Legend of Zelda: Ocarina of Time.
The code that I have achieves my intended goals fairly closely, but as the title states, the player moves around the target in a spiral pattern, rather than a perfect circle: After each revolution around the target, the player gets further and further away instead of remaining at the same distance.
I tried many different proposed solutions and looked all over, but nothing fixed this issue; please advise:
using System; using UnityEngine; public class Movement : MonoBehaviour { internal Rigidbody rb; private float x, y, z; //Float Scalar for the Vector Movement Speed public float vel; private float angleVel; private float hAxis, vAxis; internal Vector3 moveVec; //Boolean to control whether or not Movement is possible, based on other states. public bool bCanWalk; //Enemy to which the player is locked-on. public GameObject target; internal Vector3 targetterToTarget; private Vector3 crossProd; void Start() { rb = GetComponent<Rigidbody>(); rb.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ; } void Update() { //Move once per frame Move(); } void Move() { y = rb.velocity.y; hAxis = Input.GetAxisRaw("Horizontal"); vAxis = Input.GetAxisRaw("Vertical"); targetterToTarget = transform.position - target.transform.position; crossProd = MathHelper.CrossProd(target.transform.up.normalized, targetterToTarget.normalized); switch (hAxis) { case -1: case 1: x = crossProd.x * -hAxis * vel; z = crossProd.z * -hAxis * vel; break; default: angleVel = 0; x = 0; z = vAxis * vel; break; } SetMoveVec(); rb.velocity = moveVec; } private void SetMoveVec() { moveVec.x = x; moveVec.y = y; moveVec.z = z; } } using System; using UnityEngine; public static class MathHelper { public static Vector3 CrossProd(Vector3 targetForwardNormalized, Vector3 targetterToTargetNormalized) { Vector3 crossProdVar; crossProdVar.x = (targetForwardNormalized.y * targetterToTargetNormalized.z) - (targetForwardNormalized.z * targetterToTargetNormalized.y); crossProdVar.y = (targetForwardNormalized.z * targetterToTargetNormalized.x) - (targetForwardNormalized.x * targetterToTargetNormalized.z); crossProdVar.z = (targetForwardNormalized.x * targetterToTargetNormalized.y) - (targetForwardNormalized.y * targetterToTargetNormalized.x); return crossProdVar; } } Thank you.