My code is a little messy (one day of jam and such) but it goes like this:
- Player Script:
- private void Update() {
if (!dead) {
handleAim();
}
}
void handleAim() {
Vector3 mousePos = Mouse.current.position.ReadValue();
Vector3 Worldpos = Camera.main.ScreenToWorldPoint(mousePos);
weapon.Aim(Worldpos);
}
- private void Update() {
- Weapon Script:
- private void Update() { UpdateAim(); }
public virtual void Aim(Vector3 mousePos) {
aimDirection = mousePos - transform.position;
aimDirection.z = 0;
aimDirection = aimDirection.normalized;
}
public void UpdateAim() {
Vector3 currentAimDirection = transform.up;
currentAimDirection.z = 0;
currentAimDirection = currentAimDirection.normalized;
Vector3 rightDirection = transform.right;
rightDirection.z = 0;
rightDirection = rightDirection.normalized;
Debug.DrawRay(transform.position, aimDirection, Color.blue, 0.1f);
Debug.DrawRay(transform.position, currentAimDirection, Color.red, 0.1f);
float rotationDirection = Vector3.Dot(rightDirection, aimDirection);
float angularVelocity = -Mathf.Sign(rotationDirection);
float maxAngle = Vector3.Angle(currentAimDirection, aimDirection);
float rotationValue = angularVelocity * rotationSpeed * Time.deltaTime;
rotationValue = Mathf.Sign(rotationValue) * Mathf.Clamp(Mathf.Abs(rotationValue), 0, maxAngle);
transform.Rotate(0, 0, rotationValue);
}
- private void Update() { UpdateAim(); }