This code works. I use it to point GamObject
to a target, the target is placed on the screen by theplane.Raycast
. Everything works.
But I’m not a fan of duplicate code and I don’t like duplicate code, so I changed my code to get an array of Objects to aim and point them to target since everything is fired from the same Gameobject. I was wondering if it was a performer or some other method or trick would do it.
Here is the code.
→ The part I am interested in is where I get all Objects (aimAtTarget
) and aim them at the Target the For loop part.
using UnityEngine;
using UnityEngine.InputSystem;
public class HandAim : MonoBehaviour
{
private Vector3 screenPosition;
private Vector3 worldPosition;
Plane plane = new Plane(Vector3.forward, 0);
[SerializeField] Transform target;// target used for aiming at.
[SerializeField] Transform[] aimAtTarget;// Object to aim at the target
[SerializeField] float damping = 2f;
int aimAtTargetLenght;
void Awake()
{
aimAtTargetLenght = aimAtTarget.Length;
}
void Update()
{
// Position the aim target at world point
screenPosition = Mouse.current.position.ReadValue();
Ray ray = Camera.main.ScreenPointToRay(screenPosition);
if (plane.Raycast(ray, out float distance))
{
worldPosition = ray.GetPoint(distance);
}
for (int i = 0; i < aimAtTargetLenght; i++)
{
var lookPos = target.position - aimAtTarget[i].position;
lookPos.z = 0;
var rotation = Quaternion.LookRotation(lookPos);
aimAtTarget[i].rotation = Quaternion.Slerp(aimAtTarget[i].rotation, rotation, Time.deltaTime * damping);
target.position = worldPosition;
}
}
}