1,灵感来源
今天手头的工作忙完了,就等着服务器那边完活,于是开始研究同步问题。
正好想到之前想做的,两个小人对线PK,便有了这篇文章。
2,要实现的效果
如图所示,两个小人可以互相锁定,模拟真实对战,视线一直不离开对方。
最终实现效果:
套皮之后的效果:
3,基本实现原理
LookAt :保持一直看着对面
RotateAround:绕着XX物体旋转
Translate:绕着某个方向前进后退
4,基本实现方法
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class test : MonoBehaviour
{
public Transform targetTrans;
public float spd = 180f;
public float spd2 = 0.02f;
public bool isOne = true;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.LookAt(targetTrans);
if (isOne)
{
if (Input.GetKey(KeyCode.A))
{
this.transform.RotateAround(targetTrans.position, Vector3.up, spd * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D))
{
this.transform.RotateAround(targetTrans.position, Vector3.up, -spd * Time.deltaTime);
}
if (Input.GetKey(KeyCode.W))
{
transform.Translate(spd2 * Vector3.forward * Time.time, Space.Self);
}
if (Input.GetKey(KeyCode.S))
{
transform.Translate(-spd2 * Vector3.forward * Time.time, Space.Self);
}
}
else
{
if (Input.GetKey(KeyCode.RightArrow))
{
this.transform.RotateAround(targetTrans.position, Vector3.up, spd * Time.deltaTime);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
this.transform.RotateAround(targetTrans.position, Vector3.up, -spd * Time.deltaTime);
}
if (Input.GetKey(KeyCode.UpArrow))
{
transform.Translate(spd2 * Vector3.forward * Time.time, Space.Self);
}
if (Input.GetKey(KeyCode.DownArrow))
{
transform.Translate(-spd2 * Vector3.forward * Time.time, Space.Self);
}
}
}
}