Reputation: 9
I want to make a bullet follow my raycast that I use to detect whether a shot hit on an enemy. This is my script to shoot a raycast so far.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunShootingScript : MonoBehaviour
{
public ParticleSystem MuzzleFlash;
public float damage = 10f;
public float range = 100f;
public GameObject bullet;
public Camera playerCamera;
private void Update()
{
if(Input.GetKeyDown(KeyCode.Mouse0))
{
Shoot();
}
}
void Shoot()
{
MuzzleFlash.Play();
RaycastHit hit;
if(Physics.Raycast(playerCamera.transform.position, playerCamera.transform.forward, out hit, range))
{
TakeDamage target = hit.transform.GetComponent<TakeDamage>();
if(target != null)
{
target.GiveDamage(damage);
}
}
}
}
This is my script for the enemy to take damage.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TakeDamage : MonoBehaviour
{
public float health = 50f;
public void GiveDamage(float amount)
{
health -= amount;
if (health <= 0f)
{
Die();
}
}
public void Die ()
{
Destroy(gameObject);
}
// Start is called before the first frame update
}
I want the bullet to go through the raycast line created simulating a bullet being shot, what do I need to add to my code to do this?
Upvotes: 0
Views: 591
Reputation: 4711
Create a script for the Shot and place this on your shot gameObject prefab. Before or after your raycast spawn an instance of the shot and set the rotation to be the same as the player camera. In the Shot script inside of update, move the shot forward by speed * Time.deltaTime.
public class Shot : MonoBehaviour
{
public float speed;
void Update()
{
transform.position += transform.forward * speed * Time.deltaTime;
}
}
and inside of your code
...
MuzzleFlash.Play();
...
Instantiate(shotPrefab, playerCamera.transform.position, playerCamera.transform.rotation);
You will want to destroy the shot after a specified amount of time and when it hits something. You can do a raycast inside of the shots update (before you move it) from its current position to the position it will be to see if it will hit anything that frame.
Upvotes: 1