Track an object and fire?
I'm trying to make a top down shooter. There is a sentry gun, that is supposed to shoot at any "enemy" object that comes near a certain range. Basically, I want the turret to shperecast and detect an enemy, then rotate and face the object, then play fire animation and sounds. Here is the code:
public class WeaponsFire : MonoBehaviour {
private RaycastHit hit;
private Transform target;
public float senstivity = 2.0f;
private Vector3 lookpos;
Quaternion rot;
// Update is called once per frame
void Update () {
if (Physics.SphereCast(transform.position, 100, transform.forward, out hit))
{
Debug.DrawRay(transform.position, transform.up);
print("Hit something.");
if(hit.collider.tag == "Enemy")
{
print("Enemy detected!! Fire");
target = hit.collider.transform;
lookpos = target.position - transform.position;
lookpos.y = 0;
rot = Quaternion.LookRotation(lookpos);
transform.rotation = Quaternion.Slerp(transform.rotation, rot, Time.deltaTime * senstivity);
Debug.DrawLine(transform.position, target.position);
}
}
}
}
Still have to add the animation code but I can handle it. This is script is placed on the turret of the gun(its like a big machine gun). It doesn't seem to work at all, I cant even see the rays coming form Debug.DrawLine(). Please help.
EDIT: I finally got it to work kinda using overlap sphere, but the the turret rotates in the wrong direction(just opposite of the target). How to fix the rotation problem? Here is the new code:
Collider[] colliders = Physics.OverlapSphere(transform.position, 100);
while (i < colliders.Length)
{
if (colliders[i].tag == "Enemy")
{
print("Enemy Detected");
target = colliders[i].transform;
direct = target.position - transform.position;
direct.y = 0;
rot = Quaternion.LookRotation(direct);
transform.rotation = Quaternion.LerpUnclamped(transform.rotation, rot, Time.deltaTime * 0.9f);
print("Target locked on enemy");
}
i++;
}
}
This code makes the turret rotate but in the opposite direction to enemy. Also is this code better than the previous??
Your answer
Follow this Question
Related Questions
Any Clue why this is turning 180? 2 Answers
C# Door Script Problem 0 Answers
Help with raycast for for wall detection 1 Answer
Rotated object raycasting in wrong directions!!? 3 Answers
How to detect if a GameObject is currently rotating? 1 Answer