Good morning!
I’ve been trying to implement a top down shooting system. It’s working well for what I imagined the prototype to be, but I’m having a problem where I’m standing still, same rotation, shooting directly at the ground, at the same point, but It sometimes generates a ray that simply makes no sense: the ray origin is far away from the nozzle, and the hit point is far away from the actual mouse pointer.
Below, I’ve attached a screenshot which should help visualize the problem a little bit better.
I’ve logged the nozzle and mouse hit point positions, and both vary despite the GameObject remaining still.
There are three classes involved:
- Controller
- Humanoid
- Firearm
1 - In the controller class, I have the following code to rotate the character from mouse target
void TargetRotateToLookPoint()
{
bool isManualLook = false;
if (Input.GetKey(KeyCode.F))
{
player.LookAt(mouseTarget.position);
isManualLook = true;
}
else if (translateVector != Vector3.zero)
player.LookTowards(translateVector);
foreach (var layer in rigBuilder.layers)
layer.active = isManualLook;
}
which is called in FixedUpdate
2 - On the humanoid I have the following to rotate the transform itself
public void LookAt(Vector3 point)
{
Vector3 lookDirection = (point - transform.position).normalized;
LookTowards(lookDirection);
if (weapon)
weapon.transform.LookAt(point);
}
public void LookTowards(Vector3 direction)
{
Quaternion lookRotation = Quaternion.LookRotation(direction);
Quaternion planeLookRotation = new Quaternion(transform.rotation.x, lookRotation.y, transform.rotation.z, lookRotation.w);
transform.rotation = Quaternion.Slerp(transform.rotation, planeLookRotation, turnSpeed * Time.deltaTime);
}
3 - And finally, in the firearm class, just a simple raycast
public void Fire()
{
RaycastHit hit;
if (Physics.Raycast(Nozzle.position, transform.forward, out hit, 500f))
{
if (hit.collider.TryGetComponent<Humanoid>(out Humanoid humanoid))
{
humanoid.TakeDamage(1000);
}
//Humanoid hit.collider.GetComponent<Humanoid>().enabled = false;
var rayLength = Vector3.Distance(Nozzle.position, hit.point);
Debug.Log("NOZZLE POS: " + Nozzle.position.ToString() + "\nHIT POINT: " + hit.point.ToString());
Debug.DrawRay(Nozzle.position, transform.forward * rayLength, Color.red, 10);
};
}
I’m not sure if I’m doing something wrong, but any help would be appreaciated.
Thanks!
