Question by
moonlitmoon · Feb 14, 2020 at 03:50 AM ·
c#2d gameaddforcenot workinggun script
AddForce not working on Instantiated prefab
I've been trying to get projectile/prefab bullets in a top down 2d project here's the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Shooterer : MonoBehaviour {
public GameObject bullet;
public float bulletspeed;
private GameObject instbullet;
private Rigidbody2D rb;
private bool Canfire;
void Start () {
Canfire = true;
}
void Update () {
if(Canfire){
//getting direction of firing
if (Input.GetKey (KeyCode.UpArrow)){
fire ();
rb.AddForce (instbullet.transform.up * (bulletspeed/150.0f));
}
if(Input.GetKey (KeyCode.DownArrow)){
fire ();
rb.AddForce (instbullet.transform.up * (-bulletspeed/150.0f));
}
if(Input.GetKey (KeyCode.LeftArrow)){
fire ();
rb.AddForce (instbullet.transform.right * (-bulletspeed/150.0f));
}
if(Input.GetKey (KeyCode.RightArrow)){
fire ();
rb.AddForce (instbullet.transform.right * (bulletspeed/150.0f));
}
}
}
void fire(){
if (Canfire) {
//instantiate bullet
instbullet = Instantiate /*(bullet, new Vector3(0,0,0), Quaternion.identity);*/ (bullet, new Vector3 (gameObject.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z), Quaternion.identity);
//get bullet rigidbody
rb = instbullet.GetComponent<Rigidbody2D> ();
Canfire = false;
Invoke ("Canfiretruetime", 0.25f);
}
}
//Allow player to fire again
void Canfiretruetime(){
Canfire = true;
}
}
Comment
Your answer
Follow this Question
Related Questions
How to move a bullettrail the direction the player is facing 0 Answers
Selecting a game object in Unity 2d 3 Answers
NullreferenceException dealing damage to a child of the enemy 0 Answers
[C#] Enum not working properly 2 Answers
Enemy wont deal damage 0 Answers