I’m programming a grenade for my top-down shooter, but when I call Explode(), nothing detonates and nothing moves.
Any ideas?
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (Rigidbody))]
public class PlayerController : MonoBehaviour {
public GameObject bulletPrefab;
public GameObject grenadePrefab;
public Transform bulletSpawn;
public bool running;
public float radius = 1000;
public float power = 3000;
public float upForce = 1;
void Start () {
myRigidbody = GetComponent<Rigidbody> ();
}
void Update () {
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Fire();
}
if (Input.GetKey (KeyCode.LeftShift)) {
running = true;
}
else{running = false;}
if (Input.GetKeyDown (KeyCode.Mouse1)) {
Invoke ("Explode", 3);
}
if (Input.GetKeyUp (KeyCode.Mouse1)) {
Fire2();
}
}
void Fire()
{if (!running)
{
var bullet = (GameObject)Instantiate (
bulletPrefab,
bulletSpawn.position,
bulletSpawn.rotation);
bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * 40;
Destroy(bullet, 10.0f);
}
}
void Fire2()
{
{if (!running)
{
var grenade = (GameObject)Instantiate
(grenadePrefab,
bulletSpawn.position,
bulletSpawn.rotation);
grenade.GetComponent<Rigidbody>().velocity = grenade.transform.forward * 15f;
}
}
}
void Explode()
{
Vector3 explosionPosition = grenadePrefab.transform.position;
Collider[] colliders = Physics.OverlapSphere(explosionPosition, radius);
foreach (Collider hit in colliders)
{
Rigidbody rb = hit.GetComponent<Rigidbody>();
if (rb != null) {
Debug.Log ("BEEP");
rb.AddExplosionForce (power, explosionPosition, radius, upForce);
}
}
}
Vector3 velocity;
Rigidbody myRigidbody;
public void Move(Vector3 _velocity) {
velocity = _velocity;
}
public void LookAt(Vector3 lookPoint) {
Vector3 heightCorrectedPoint = new Vector3 (lookPoint.x, transform.position.y, lookPoint.z);
transform.LookAt (heightCorrectedPoint);
}
public void FixedUpdate() {
myRigidbody.MovePosition (myRigidbody.position + velocity * Time.fixedDeltaTime);
}
}