Hello everyone,
I am trying to use Linecast2D in my game but I didn’t able to get the result I want.
In my 2D strategy game Point Defense Turrets can intercept incoming enemy missiles, as you can see in the image above. When Linecast successfully hit the target missile, Turret should rotate toward the target missile. But it’s not happening. Because currently Force Field is blocking the Linecast.
This is my script attached on Point Defence Turret
void Start()
{
if(transform.parent.localPosition.y > 0)
{
defaultRotation = Quaternion.Euler(0, 0 , 90);
}
else if(transform.parent.localPosition.y < 0)
{
defaultRotation = Quaternion.Euler(0, 0 , -90);
}
transform.localRotation = defaultRotation;
}
private int layerMask = 8;
void FixedUpdate()
{
// Closest Missile is closestTarget
if(closestTarget != null)
{
RaycastHit2D hit = Physics2D.Linecast(firePoint.position, closestTarget.position, layerMask);
if(hit)
{
Debug.Log(hit.transform.name);
// Something is blocking Linecast so rotate Turret to default State.
transform.localRotation = Quaternion.Slerp(transform.localRotation, defaultRotation, Time.deltaTime * rotateSpeed);
}
else
{
// Linecast successfully hitting the target missile, so rotate toward the missile
distanceFromMissile = Vector3.Distance (transform.position, closestTarget.position);
if(distanceFromMissile < 40)
{
Vector3 vectorToTarget = closestTarget.position - transform.position;
float angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * rotateSpeed);
}
}
}
}
Let me know if you have any doubts.
Please help me, I am having trouble understanding Linecast and LayerMask from months.
