- Home /
shooting raycast
every thing is working fine but its instantiating the bullet around the player and not shooting it here the script using JetBrains.Annotations; using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityEngine.SocialPlatforms;
public class shootingforshutgun : MonoBehaviour
{
public Transform ponit;
public float Speed =10f;
public GameObject bullet;
bool canshot = false;
int Bullets = 10;
int currentbullet;
bool reloading = false;
int range = 100;
int howmanytimes = 8;
void Start()
{
currentbullet = Bullets;
}
// Update is called once per frame
void Update()
{
if(Input.GetButtonDown("Fire1"))
{
shoot();
}
Debug.Log(currentbullet);
}
public void shoot()
{
float x = Random.Range(-10f, 10f);
float y = Random.Range(-10f, 10f);
Vector3 a = new Vector3(x , y);
Vector3 c = transform.forward + a;
if (!canshot)
{
RaycastHit hit;
if (Physics.Raycast(ponit.position,c , out hit, range))
{
Instantiate(bullet, hit.point, Quaternion.LookRotation(hit.normal));
}
}
currentbullet--;
}
}
Answer by KoenigX3 · May 30, 2020 at 10:37 AM
Does bullet have a script to manage its movement? If not, then you need to put a RigidBody on it, and you must access it after instantiating.
GameObject bullet = Instantiate(bullet, hit.point, Quaternion.LookRotation(hit.normal));
bullet.GetComponent<RigidBody>().AddForce(bullet.tranform.forward * 100, ForceMode.Impulse);
You can of course use a variable instead of 100. Also, make sure that the bullet prefab is looking at the forward axis, otherwise it won't go forward. Keep in mind that if you are using this method to create collisions, you need to change the RigidBody's collision detection mode if the bullet is too fast. You can read about this on the UnityDocs website.
ok thank you it worked but why did you store the Instantiate method in a variable?
I stored the GameObject in a temporary variable called bullet so i can get the RigidBody component. If you check Instantiate, it returns the instantiated GameObject so you can optionally store it and use it if you need to (to set it inactive, or for other reasons). The variable itself is local, so it gets discarded after it is out of scope.
Your answer
Follow this Question
Related Questions
scripting problem 0 Answers
Multiplayer FPS Bullets: should they be rigid bodies or raycast? 1 Answer
How to get bullets to hit crosshair 2 Answers
Why do I sometimes hit my Collider and sometimes not 1 Answer
fps shooting enemy 1 Answer