Question by
FlyingTurtleMan · Nov 07, 2017 at 09:31 PM ·
collisionraycasthit2d2dplatformer
Oject not detecting when being shot at
When I shoot a crate in my game, it is not being detected. What do I do? Shooting Code:
public class shoot : MonoBehaviour {
public LayerMask whatToHit;
public Transform BulletTrailPrefab;
Transform firePoint;
Transform hitPoint;
// Use this for initialization
void Awake()
{
firePoint = transform.Find("FirePoint");
if (firePoint == null)
{
Debug.LogError("Boi there be no firepoint");
}
hitPoint = transform.Find("HitPoint");
if (hitPoint == null)
{
Debug.LogError("Boi there be no hitpoint");
}
}
// Update is called once per frame
void Update ()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
Vector2 firePointPosition = new Vector2(firePoint.position.x, firePoint.position.y);
Vector2 hitPointPosition = new Vector2(hitPoint.position.x, hitPoint.position.y);
RaycastHit2D hit = Physics2D.Raycast(firePointPosition, hitPointPosition - firePointPosition, 100, whatToHit);
Effect(hitPointPosition, firePointPosition);
Debug.DrawLine(firePointPosition, (hitPointPosition - firePointPosition) * 100, Color.magenta);
if (hit.collider != null)
{
Debug.DrawLine(firePointPosition, hit.point, Color.green);
Enemy enemy = hit.collider.GetComponent<Enemy>();
crate Crate = hit.collider.GetComponent<crate>();
if (Crate != null)
{
Debug.Log("The crate has been broken");
Crate.Suicide();
}
if (enemy != null)
{
Debug.Log("you shot the enemy");
enemy.DamageEnemy(PlayerStats.damage);
}
}
}
void Effect(Vector2 hitPointPosition, Vector2 firePointPosition)
{
Vector3 dir = hitPointPosition - firePointPosition;
dir.x = 0; //or try dir.x = 0;
Instantiate(BulletTrailPrefab, firePoint.position, Quaternion.LookRotation(dir));
}
}
Crate script: public class crate : MonoBehaviour {
public void Suicide()
{
Destroy(this);
}
}
Comment
Your answer
Follow this Question
Related Questions
physic2D.overlapArea Generate Collision? 0 Answers
Issue with character movement and collision using Physics2D.Raycast. 0 Answers
Raycast collisions being detected along a non-existent curve(?) 1 Answer
two boxCasts casted from same point give different results 0 Answers
Physics object bouncing on collision. 0 Answers