So, I just started to try and develop my first multiplayer prototyp. I plan on using UNet but it seems like there isn’t a lot of tutorials/help/etc. out there already. I found a few helpfull infos though. My problem is that most of them are meant for first person style games and just sync the movement a player makes - so maybe if you know something thats more fitting to my case I’d be thankfull ![]()
Anyways, what I try to achieve is a controll scheme similar to RTS, MOBA, Hack 'n Slay (so practically mouse click to move). Also the server should do all the movement, player only send in theire orders/mouse click (to prevent cheating).
I created something that works, howerver movement is still quite stuttering so I’d be glad if you could give me some pointers of what I’m doing wrong.
Here’s my code so far
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class Player_SyncPosition : NetworkBehaviour {
[SyncVar]
private Vector3 syncPos;
private bool isMoving = false;
private Vector3 endPos;
[SerializeField]
Transform myTransform;
[SerializeField]
float lerpRate = 15;
[SerializeField]
float speed = 10f;
//vertical position of the gameobject
private float yAxis;
void Start()
{
//save the y axis value of gameobject
yAxis = gameObject.transform.position.y;
}
void FixedUpdate () {
if (hasAuthority)
{
Cmd_UpdateMovement();
}
}
void Update()
{
if (isLocalPlayer)
{
CheckForClick();
}
LerpPosition();
}
[ClientCallback]
void CheckForClick()
{
if (Input.GetMouseButtonDown(0))
{
//declare a variable of RaycastHit struct
RaycastHit hit;
//Create a Ray on the clicked position
Ray ray;
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//Check if the ray hits any collider
if (Physics.Raycast(ray, out hit))
{
//save the click position
Vector3 clickPos = hit.point;
//reset to original y axis value
clickPos.y = yAxis;
Cmd_ComputeMovementPoint(clickPos);
}
}
}
void LerpPosition()
{
myTransform.position = Vector3.Lerp(myTransform.position, syncPos, Time.deltaTime * lerpRate);
}
[Command]
void Cmd_ComputeMovementPoint(Vector3 pos)
{
endPos = pos;
//set a flag to indicate that the gameobject is moving
isMoving = true;
}
[Command]
void Cmd_UpdateMovement()
{
if (isMoving && !Mathf.Approximately(myTransform.position.magnitude, endPos.magnitude))
{
//move the gameobject to the desired position
myTransform.position = Vector3.Lerp(myTransform.position, endPos, 1 / (speed * (Vector3.Distance(myTransform.position, endPos))));
syncPos = myTransform.position;
}
//set the movement indicator flag to false if the endPoint and current gameobject position are equal
else if (isMoving && Mathf.Approximately(myTransform.position.magnitude, endPos.magnitude))
{
isMoving = false;
}
}
}