Racasthit2d range not working
When I shoot my gun from a far distance the raycast doesn't detect the other player. But when the player is touching the other player it works. here is my script.
using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI;
public class ShootingScript1 : NetworkBehaviour { //public ParticleSystem _muzzleFlash; //public AudioSource _gunAudio; public GameObject _impactPrefab; public Transform ray;
ParticleSystem _impactEffect;
public int gunDamage = 25;
public float range;
public float fireRate;
public LayerMask whatToHit;
void Start()
{
_impactEffect = Instantiate(_impactPrefab).GetComponent<ParticleSystem>();
}
void Update()
{
if (Input.GetButtonDown("Fire1"))
{
//_muzzleFlash.Stop();
//_muzzleFlash.Play();
//_gunAudio.Stop();
//_gunAudio.Play();
RaycastHit2D hit = Physics2D.Raycast(ray.position, Vector2.zero, range, whatToHit);
if (hit.transform.gameObject.tag == "Player")
{
//Health health = hit.transform.GetComponent<Health>();
_impactEffect.transform.position = hit.point;
_impactEffect.Stop();
_impactEffect.Play();
Debug.Log("Hit");
//Destroy(gameObject);
CmdHitPlayer(hit.transform.gameObject);
}
}
}
[Command]
void CmdHitPlayer(GameObject hit)
{
hit.GetComponent<NetworkedPlayerScript>().RpcResolveHit();
}
}
Have you tried drawing gizmos to see where that raycast is actually going? Also, that's a Physics call running in Update(). For more reliable results, those sorts of things typically go in FixedUpdate().
Answer by TreyH · Nov 01, 2016 at 04:39 PM
Also, your raycast direction is set to Vector2.zero. Your ray will follow this path:
Start --> Start + Direction * magnitude.
In your case, the direction is zero, so your ray will only hit things that come within your object itself -- this might explain your issue. For an example, attach this to something and make sure Gizmos are enabled in your editor. Rotate it around in the inspector to see what happens:
using UnityEngine;
using System.Collections;
public class GizmoTest : MonoBehaviour {
// Draw rays, primatives, and whatnot to test your orientations.
void OnDrawGizmos () {
// Create the ray you want to check
float rayLength = 10f;
// Then draw it
Gizmos.DrawRay(this.transform.position, this.transform.up * rayLength );
}
}