- Home /
Question by
Kartik0411 · Jan 13, 2020 at 07:00 AM ·
collisionraycastcollision detectionlinerenderershooter
Melee Attack - Kill Enemy on Contact with a ray
Hi, I am trying to kill an enemy the moment it comes in contact with the ray i.e. the weapon (similar to Lightsaber) is activated on the press of the mouse button and is active until the button is released. Any object (Enemy) is killed on the touch of this ray. I am using a line renderer and Raycast. This is part of the shooter survival game for learning purpose. I am new to Unity. Any help would be appreciated. Thanks in advance.
using UnityEngine;
public class PlayerShooting01 : MonoBehaviour { public int damagePerShot = 100;
public float timeBetweenBullets = 0.15f;
public float range = 2.5f;
float Distance;
float MaxDistance = 3;
float timer;
Ray shootRay;
RaycastHit shootHit;
RaycastHit hit;
int shootableMask;
ParticleSystem gunParticles;
LineRenderer gunLine;
AudioSource gunAudio;
Light gunLight;
float effectsDisplayTime = 0.2f;
void Awake()
{
shootableMask = LayerMask.GetMask("Shootable");
gunParticles = GetComponent<ParticleSystem>();
gunLine = GetComponent<LineRenderer>();
gunAudio = GetComponent<AudioSource>();
gunLight = GetComponent<Light>();
}
void Update()
{
timer += Time.deltaTime;
if (Input.GetButtonDown("Fire1"))
{
timer = 0f;
gunAudio.Play();
gunLight.enabled = true;
gunParticles.Stop();
gunParticles.Play();
gunLine.enabled = true;
gunLine.SetPosition(0, transform.position);
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward),out hit, shootableMask))
{
EnemyHealth enemyHealth = /*not sure what to do here*/ hit.collider.GetComponent<EnemyHealth>();
if (enemyHealth != null)
{
enemyHealth.TakeDamage(damagePerShot, hit.point);
}
}
}
/* if (Input.GetButtonDown("Fire1"))
{
// ... shoot the gun.
Shoot();
}*/
if (Input.GetButtonUp("Fire1"))
{
DisableEffects();
}
gunLine.SetPosition(0, transform.position);
shootRay.origin = transform.position;
gunLine.SetPosition(1, shootRay.origin + shootRay.direction * range);
shootRay.direction = transform.forward;
}
public void DisableEffects()
{
gunLine.enabled = false;
gunLight.enabled = false;
}
/*void Shoot()
{
timer = 0f;
gunAudio.Play();
gunLight.enabled = true;
gunParticles.Stop();
gunParticles.Play();
gunLine.enabled = true;
gunLine.SetPosition(0, transform.position);
shootRay.origin = transform.position;
shootRay.direction = transform.forward;
if (Physics.Raycast(shootRay, out shootHit, range, shootableMask))
{
if (shootHit.transform.tag == "new")
{
EnemyHealth enemyHealth = shootHit.collider.GetComponent<EnemyHealth>();
if (enemyHealth != null)
{
enemyHealth.TakeDamage(damagePerShot, shootHit.point);
}
gunLine.SetPosition(1, shootRay.origin + shootRay.direction * range);
}
}
}*/
}
Comment