- Home /
How can I add force to a raycast bullet?
I'm working in a FPS. I've got a GunScript that instantiates a basic "bullet" when mouse button is pressed. The bullet uses raycast. What i wanted to do is to add force to the rigidbodies that the bullet hits, so it could shoot to objects (boxes, enemies, etc) and make them move by the force of the impact.
But for any reason it's not working! I would be glad if you lend me a hand on this, guys..
What I tried is defining:
var bulletDirection = transform.TransformDirection(Vector3.forward);
and then use:
hit.rigidbody.AddForceAtPosition (bulletDirection * bulletForce, hit.point);
this is the script:
var range : float = 50;
var bulletHole : GameObject;
var blood : GameObject;
var floatHeight : float = 0.001;
var damage : float = 1;
var bulletForce : float = 10000;
function Update ()
{
var hit : RaycastHit;
// var bulletDirection = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, transform.forward, hit, range))
{
if (bulletHole && hit.transform.tag == "bulletHoleReceiver")
Instantiate(bulletHole, hit.point + (hit.normal * floatHeight), Quaternion.LookRotation(hit.normal));
if (blood && hit.transform.tag == "Enemy")
{
// hit.rigidbody.AddForceAtPosition (bulletDirection * bulletForce, hit.point);
Instantiate(blood, hit.transform.position, hit.transform.rotation);
hit.transform.GetComponent(EnemyScript).enemyHealth -= damage;
}
}
Destroy(gameObject);
}
Sorry for my poor english.
Answer by Cinematronic · Oct 28, 2012 at 10:36 AM
The solution was using a tag on the objects I wanted to have bullet physics and then add:
if (hit.transform.tag == "Physics")
{
hit.rigidbody.AddForceAtPosition (bulletDirection * bulletForce, hit.point);
}
It works great. Thanks!
Answer by SavvaMadar · Oct 05, 2012 at 12:14 AM
Just a suggestion... Check from where the raycast is being spawned, I had a similar problem. I had to go and rotate my model in an editor before the rays shot correctly.
Your answer
Follow this Question
Related Questions
Using Raycast to shoot a bullet sometimes goes through objects 0 Answers
Hit enemy life with raycast 1 Answer
Bullet Effect 2 Answers
How do I create bullet hole for my gun? 0 Answers