- Home /
The question is answered, right answer was accepted
Raycasthit2d isnt working.
I'm trying to programm multiplayer 2d game with a shoot function. you can see my shoot script below, but i cant hit something except of my own player. If i select that im also allowed to shoot myslef its working (LayerMask).
However, this line of code -Debug.Log ("Shot: " + _hit.collider.name);- isnt working if i hit the ground;
using UnityEngine.Networking;
using UnityEngine;
public class PlayerShoot : NetworkBehaviour {
private const string LOCAL_PLAYER_LAYER = "LocalPlayer";
public PlayerWeapon weapon;
[SerializeField]
private Transform player;
[SerializeField]
private LayerMask mask;
void Start() {
}
void Update(){
if(Input.GetKeyDown(KeyCode.F)){
Shoot ();
}
}
[Client]
public void Shoot(){
RaycastHit2D _hit = Physics2D.Raycast(player.position, player.forward, weapon.range, mask);
if (_hit.collider != null)
{
if (_hit.collider.tag == "Player")
{
//Debug.Log ("We hit " + _hit.collider.name);
CmdPlayerShot(_hit.collider.name);
}
// We hit something, call the OnHit method on the server
//CmdOnHit(_hit.point, _hit.normal);
Debug.Log ("Shot: " + _hit.collider.name);
}
}
[Command]
void CmdPlayerShot(string _ID) {
Debug.Log (_ID + " has been shot.");
}
If an other player is joining he's on the RemotePlayer Layer.
Answer by Crightub · Nov 16, 2017 at 04:07 PM
Fixed it. i used player.forward for the dircetion, but i a 2d game i shoot the raycast INTO the game. So it hits nothing. You have to use player.right or player.up.
Answer by smkmth · Nov 15, 2017 at 06:07 PM
dont know for sure, literally just guessing here - but i feel you need a hit.collider.gameObject.name to return the game objects name and not the attached collider's name - like i said, litearlly just a guess, i am new at this.
Nope. Isn't working. Line 31 isn't working, becuase if put a Debug.Log in the if function i wont be triggered. so _hit.collider is always null;
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Raycasting2D to Compare Tag of GameObject 1 Answer
Raycast2D not returning any transform instead keeps returning void. 1 Answer
How to get co-ordinates of end point of Raycast2D ? 1 Answer
Raycast2D/Line Renderer offset on colliders based on mouse position 0 Answers