Unity – Ray casting only works from origin

  Kiến thức lập trình

I am trying to shoot a ray from the position of my gun in the direction my mouse is at when i click shoot.

This works when my character is in the centre of the screen but then offsets in whatever distance I move away from the origin.

Itill has the same origin point of the ray (my gun) but the direction of the ray will not be where my mouse is (will be ofsett by my distance from 0,0,0).

Have tried numerous fixes, would appreciate any help.





using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class Gun : MonoBehaviour
{
    // Start is called before the first frame update

    public int gunDamage = 5;

    [SerializeField] Vector3 worldPosition;
    Vector3 mousePos;
    void Start()
    {
        
    }

    // Update is called once per frame
    void FixedUpdate()
    {
       
        worldPosition.z = 0;


        if (Input.GetMouseButtonDown(0))

            {
            mousePos = Input.mousePosition;
            //mousePos.z = Camera.main.nearClipPlane;
            worldPosition = Camera.main.ScreenToWorldPoint(mousePos);
            worldPosition.z = 0;
            RaycastHit2D hits = Physics2D.Raycast(transform.position, worldPosition);
             Debug.DrawRay(transform.position, worldPosition);
           
            if(hits.collider != null)
            {
                Health es = hits.collider.GetComponent<Health>();
                es.TakeDamage(gunDamage);
            }

        }

       
    }
}




Have tried using Vector 3 and 2. also tried using a ray to calc the position of the mouse instead of using screentoworldpoint. same issue.

New contributor

John McCann is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT