i need help with raycast
Hi, i started to make a twin stick shooter and made some bullet prefabs to work with but i discovered that the hit detection is stupid, i found that it could be posible to make bullets with raycast but i am dum at this please help
Answer by Jessespike · Aug 20, 2016 at 08:19 AM
Give it an attempt. Ask for help if you get stuck, as in post your code and describe the problem.
using UnityEngine;
using System.Collections;
public class Gun : $$anonymous$$onoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void FixedUpdate()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, -Vector3.forward, out hit))
print("Found an object - distance: " + hit.distance);
}
public void Shoot()
{
}
}
i have made a script that activates the void Shoot, and i want when its activated check if the raycast hit the enemy and decrease its life
@SQAURE-BADGER
When the raycast hits something, check if it's an enemy. Enemies have a EnemyHealth script attached to them. EnemyHealth stores a int to represent health. If health is 0 or below, then it dies.
Gun.cs
using UnityEngine;
using System.Collections;
public class Gun : $$anonymous$$onoBehaviour {
void Update() {
if (Input.Get$$anonymous$$ouseButtonDown(0))
{
Shoot();
}
}
public void Shoot() {
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit))
{
print("Found an object - distance: " + hit.distance);
// if hit is an enemy, then reduce it's health
EnemyHealth enemy = hit.transform.GetComponent<EnemyHealth>();
if (enemy != null)
{
enemy.ReduceHealth(10);
}
}
}
}
here's the EnemyHealth script
using UnityEngine;
using System.Collections;
public class EnemyHealth : $$anonymous$$onoBehaviour {
public int health = 100;
void Update() {
if (health <= 0)
{
Destroy(gameObject);
}
}
public void ReduceHealth(int amt) {
health = health - amt;
}
}
Your answer
Follow this Question
Related Questions
Raycast not taking full length 0 Answers
Scripting Errors 1 Answer
Raycast not detected on instantiated object 0 Answers
I'm trying to use a ray to grab objects but, my script isn't working? 0 Answers
Raycast Enemy AI shooting script 1 Answer