这里只写实现,UI界面自行考虑
1.主角
public class PlayerMove : MonoBehaviour
{
private Rigidbody player;
public float speed = 5;
private int groundLayerIndex = -1;
public GameObject FireBtn;
void Start()
{
player = GetComponent<Rigidbody>();
groundLayerIndex = LayerMask.GetMask("ground");
}
void FixedUpdate()
{
//控制人物WSAD按键移动
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
player.MovePosition( transform.position + new
Vector3(h,0,v)*speed*Time.deltaTime);
//防止点击按钮时因射线检测引起人物转动
RectTransform rctTr = FireBtn.GetComponent<RectTransform>();
//如果Canvas为Overlay不需要传Camera参数,否则需要传Camera
//Canvas canvas = GetComponent<Canvas>();
//Camera camera = canvas.renderMode == RenderMode.ScreenSpaceOverlay
? null : Camera.main;
bool isContain =
RectTransformUtility.RectangleContainsScreenPoint(rctTr, Input.mousePosition,
null);
if (isContain)
{
//点到开火按钮
return;
}
else
{
//点击鼠标左键,让人物朝向点击方向
if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo, 100, groundLayerIndex))
{
Vector3 target = hitInfo.point;
target.y = transform.position.y;
transform.LookAt(Vector3.Lerp(transform.position, target,
3f * Time.deltaTime));
}
}
}
}
}
2.子弹
public class BoltMove : MonoBehaviour
{
//子弹实体的自身运动控制
private Rigidbody bolt;
public float speed = 10;
void Start()
{
bolt = GetComponent<Rigidbody>();
bolt.velocity = transform.forward * speed;
}
}
3.开火
public class FireControl : MonoBehaviour
{
public Transform boltSpwan;
public GameObject bolt;
//开火按钮的点击事件
public void Fire()
{
Instantiate(bolt,boltSpwan.position,boltSpwan.rotation);
}
}
今日推荐