Hello everyone, I try to reach the movement mechanism of the join clash game
I wrote a code but it’s not the thing that I try to achieve. it would be great if you help me or guild me. thank you in advance
using UnityEngine;
public class test : MonoBehaviour
{
//********************************
public bool MoveByTouch;
private Vector3 _mouseStartPos,PlayerStartPos;
[Range(0f,100f)] public float maxAcceleration;
private Vector3 move,direction;
public Transform target; // the player will look at this object, which is in front of it
void Start()
{
maxAcceleration = 10f;
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Plane plane = new Plane(Vector3.up, 0f);
float Distance;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (plane.Raycast(ray, out Distance))
{
_mouseStartPos = ray.GetPoint(Distance);
PlayerStartPos = transform.position;
}
MoveByTouch = true;
}
else if (Input.GetMouseButtonUp(0))
{
MoveByTouch = false;
}
if (MoveByTouch)
{
Plane plane = new Plane(Vector3.up, 0f);
float Distance;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (plane.Raycast(ray, out Distance))
{
var newray = ray.GetPoint(Distance);
move = newray - _mouseStartPos;
var controller = PlayerStartPos + move;
controller.x = Mathf.Clamp(controller.x, -8f, 8f);
var TargetNewPos = target.position;
TargetNewPos.x = Mathf.MoveTowards(TargetNewPos.x,controller.x , 80f * Time.deltaTime);
TargetNewPos.z = Mathf.MoveTowards(TargetNewPos.z, 1000f, 10f * Time.deltaTime);
target.position = TargetNewPos;
var PlayerNewPos = transform.position;
PlayerNewPos.x = Mathf.MoveTowards(PlayerNewPos.x, controller.x, maxAcceleration * Time.deltaTime);
PlayerNewPos.z = Mathf.MoveTowards(PlayerNewPos.z, 1000f, 10f * Time.deltaTime);
transform.position = PlayerNewPos;
for (int i = 0; i < transform.childCount; i++)
{
Vector3 relativePos = target.position - transform.GetChild(i).position;
Quaternion rotation = Quaternion.LookRotation(relativePos, direction);
transform.GetChild(i).rotation = rotation;
}
}
}
else
{
MakePlayerlookforward();
}
}
void MakePlayerlookforward()
{
for (int i = 0; i < transform.childCount; i++)
transform.GetChild(i).rotation = Quaternion.Slerp(transform.GetChild(i).rotation,Quaternion.identity, 10f * Time.deltaTime);
}
}