- Home /
Why will the raycast not work on the client?
I have it so that both the host and client can spawn cubes on the map by clicking on it at the beginning of the game. I can spawn cubes perfectly on the server but it spawns the cubes at (0,0,0) on the client. Here is the current script.
[SerializeField] public Transform shootLocation;
[SerializeField] public GameObject cannonBall;
[SerializeField] public float shootingSpeed;
[SerializeField] public static int blocks;
[SerializeField] public GameObject cube;
private Vector3 dropLocation;
void Start () {
blocks = 5;
}
void Update () {
if (Input.GetMouseButtonDown(0))
{
if (blocks > 0)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (hit.transform.name != "null" && hit.transform.name != "wall")
{
dropLocation = new Vector3(hit.point.x, hit.point.y + 1.5f, hit.point.z);
CmdSpawn();
}
}
}
else
{
CmdFire();
}
}
}
[Command]
void CmdSpawn()
{
blocks = blocks - 1;
var block = Instantiate(cube, dropLocation, Quaternion.identity);
NetworkServer.Spawn(block);
}
[Command]
void CmdFire()
{
var shell = Instantiate(cannonBall, shootLocation.position, shootLocation.rotation);
shell.GetComponent<Rigidbody>().velocity = shell.transform.forward * shootingSpeed;
NetworkServer.Spawn(shell);
}
}
It seems that when CmdSpawn is called, it is called for the host and not the client. Any help to get it spawned on the client will be greatly appreciated.
Answer by ChrisKurhan · Dec 02, 2017 at 04:36 PM
If you change your CmdSpawn()
to have CmdSpawn(Vector3 dropLocation)
it should spawn the block at the expected location. Right now you assign dropLocation
on the client in Update
but this is not synced to the server in any way. I would expect your Raycast is working correctly but the Server does not know where to spawn your object.
As for CmdFire
, you also probably will need to add the position and rotation as arguments unless you're using a NetworkTransform
and the transform's position and rotation are already synchronized across Client/Server
It works! Thank you, I was about to give up and it was getting very frustrating. I will now try to continue on with the game and hopefully finish it soon.
Answer by Awesomeness1075 · Nov 29, 2017 at 03:20 AM
I did some more testing and found that the cannon balls do spawn properly. Could it be a problem with the raycast or possibly its components?