Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Bug Particle effect is getting spawned at wrong place.

Discussion in 'Editor & General Support' started by sahilsharma220202004, Aug 9, 2021.

  1. sahilsharma220202004

    sahilsharma220202004

    Joined:
    Nov 18, 2020
    Posts:
    33
    Code (CSharp):
    1. public class Weapon : MonoBehaviour
    2. {
    3.     [SerializeField] private float range = 100f;
    4.     [SerializeField] private float damage = 40f;
    5.     [SerializeField] private float impactForce = 30f;
    6.     [SerializeField] private float fireRate = 25f;
    7.  
    8.     [SerializeField] private ParticleSystem nozzleEffect;
    9.     [SerializeField] private ParticleSystem impactEffect;
    10.     private Camera mainCamera;
    11.  
    12.     private float nextShootTime;
    13.     private float nextTimeToFire = 0f;
    14.  
    15.     // Start is called before the first frame update
    16.     void Start()
    17.     {
    18.         nextShootTime = Time.deltaTime;
    19.         mainCamera = Camera.main;
    20.     }
    21.  
    22.     // Update is called once per frame
    23.     void Update()
    24.     {
    25.         if (Input.GetButton("Fire1") && Time.time >= nextTimeToFire)
    26.         {
    27.             nextTimeToFire = Time.time + 1 / fireRate;
    28.             Shoot();
    29.         }
    30.     }
    31.  
    32.     void Shoot()
    33.     {
    34.         nozzleEffect.Play();
    35.         Ray ray = new Ray(mainCamera.transform.position, mainCamera.transform.forward);
    36.         RaycastHit hitInfo;
    37.         if (Physics.Raycast(ray, out hitInfo, range))
    38.         {
    39.             Target target = hitInfo.collider.GetComponent<Target>();
    40.             if (target != null)
    41.             {
    42.                 target.TakeDamage(damage);
    43.             }
    44.             if (hitInfo.rigidbody != null)
    45.             {
    46.                 hitInfo.rigidbody.AddForce(-hitInfo.normal * impactForce, ForceMode.Impulse);
    47.             }
    48.  
    49.             ParticleSystem ImpactEffect = Instantiate(impactEffect, hitInfo.point, Quaternion.LookRotation(hitInfo.normal));
    50.             Destroy(ImpactEffect.gameObject, 2f);
    51.         }
    52.     }
    53. }
     
  2. sahilsharma220202004

    sahilsharma220202004

    Joined:
    Nov 18, 2020
    Posts:
    33
    I have used unity 1st person starter assets and combined a weapon with it to make it a fps. Now I want a particle effect "impact effect" to be spawned at the place where my ray hits something
    But if I press w for forward with any key ,particle is getting spawned at player's head.
    How to fix this and spawn particles at the place the ray hits.