Reputation: 31
When I shoot my bullet on a rigid body, it just moves in the wrong direction (to the right, when it is supposed to go forward) Here is the script that handle bullet and target interactions. I have no idea why this isn't working and help would be appreciated. thx
using UnityEngine;
public class Gun : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public float fireRate = 15f;
public float impactForce = 200f;
public ParticleSystem muzzleFlash;
private float nextTimeToFire = 0f;
public Camera fpsCam;
// Update is called once per frame
void Update()
{
if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire)
{
nextTimeToFire = Time.time + 1f / fireRate;
Shoot();
}
}
void Shoot()
{
muzzleFlash.Play();
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Target target = hit.transform.GetComponent<Target>();
if (target != null)
{
target.TakeDamage(damage);
hit.rigidbody.AddForceAtPosition(transform.forward * impactForce, hit.point);
}
}
}
}
Upvotes: 0
Views: 64
Reputation: 4049
You're using the wrong transform to get the forward
vector from.
if (target != null)
{
target.TakeDamage(damage);
hit.rigidbody.AddForceAtPosition(transform.forward * impactForce, hit.point);
}
should be:
if (target != null)
{
target.TakeDamage(damage);
hit.rigidbody.AddForceAtPosition(fpsCam.transform.forward * impactForce, hit.point);
}
Upvotes: 2