I’m trying to fire a ray and then spawn an object at that location. It works perfectly fine on the server, but on any clients the placement is offset and I can’t figure out why for the life of me. Here’s a picture to describe what I mean in more detail.
And here’s my code:
using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
public class Building_MP : NetworkBehaviour {
[SerializeField]
GameObject GhostGO;
[SerializeField]
LayerMask LM;
bool snap = false;
int ghostID;
// Use this for initialization
void Start () {
ghostID = Random.Range(0, 10000);
}
// Update is called once per frame
void Update () {
if(Input.GetButtonDown("Fire2") && isLocalPlayer)
{
CmdSpawnGhostBrick();
}
if(isLocalPlayer)
{
//CmdMoveGhostBrick();
if (Input.GetKeyDown(KeyCode.B))
{
snap = !snap;
}
}
}
[Command]
void CmdSpawnGhostBrick()
{
RaycastHit hit;
Ray ray = GetComponentInChildren<Camera>().ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 200.0f, LM))
{
GameObject ghostBrick = Instantiate(GhostGO, new Vector3(RoundToHalf(hit.point.x), RoundToHalf(hit.point.y), RoundToHalf(hit.point.z)), Quaternion.identity) as GameObject;
ghostBrick.transform.name = "GhostBrick (" + ghostID + ")";
ghostBrick.transform.tag = "Ghost";
ghostBrick.layer = 10;
NetworkServer.Spawn(ghostBrick);
Debug.Log("Hit at " + hit.point.ToString());
Debug.Log("BrickPos " + ghostBrick.transform.position);
}
}
[Command]
void CmdMoveGhostBrick()
{
GameObject ghostBrick = GameObject.Find("GhostBrick (" + ghostID + ")");
if(ghostBrick != null)
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100.0f, LM))
{
if (!snap)
{
ghostBrick.transform.position = new Vector3(RoundToHalf(hit.point.x), RoundToHalf(hit.point.y) + ghostBrick.GetComponent<Renderer>().bounds.size.y / 2, RoundToHalf(hit.point.z));
}
else
{
ghostBrick.transform.position = new Vector3(hit.transform.position.x, hit.transform.position.y + ghostBrick.GetComponent<Renderer>().bounds.size.y, hit.transform.position.z);
}
}
if(Input.GetButtonDown("Fire1"))
{
GameObject newBrick = Instantiate(GhostGO, ghostBrick.transform.position, ghostBrick.transform.rotation) as GameObject;
NetworkServer.Spawn(newBrick);
}
}
}
[Command]
void CmdDestroyGhost()
{
GameObject ghostBrick = GameObject.Find("GhostBrick (" + ghostID + ")");
if(ghostBrick != null)
{
NetworkServer.Destroy(ghostBrick);
}
}
public static float RoundToHalf(float f)
{
return f = Mathf.Round(f * 4f) * 0.25f;
}
}
Thanks a ton in advance, I’m at my wit’s end right now.