本帖最后由 da11 于 2021-5-31 15:42 编辑
//自写案例,之后如有优化会在本帖回复!
//Walk.cs
//挂在主角对象中
//左右移动,Vector3坐标使用的是X轴!!
//上下移动,Vector3坐标使用的是Z轴!!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 玩家行为类
/// </summary>
public class Walk : MonoBehaviour
{
private Transform PlayerTransform; //声明主角Transform类字段
public GameObject PlayerWeaponsAttackVar; //声明主角攻击武器GameObject类字段,注意是public公开类型,测试阶段可以直接在Unity编辑器中拖拽主角攻击武器游戏对象
private DHPlay DHPlayVar; //声明之前的播放动画工具类字段
public float PlayerWalkSpeed; //声明主角行动速度字段
private void Start()
{
PlayerTransform = this.transform;
PlayerWalkSpeed = 0.2f;
DHPlayVar = new DHPlay(this.GetComponentInChildren<Animation>());
}
private void Update()
{
/* 暂时注释,为主角使用Input类输入控制前后左右移动
if (Input.GetKey(KeyCode.W))
{
//PlayerTransform.LookAt(Vector3.forward);
PlayerTransform.Translate(Vector3.forward * PlayerWalkSpeed);
}
if (Input.GetKey(KeyCode.S))
{
//PlayerTransform.LookAt(Vector3.back);
PlayerTransform.Translate(Vector3.back * PlayerWalkSpeed);
}
*/
/*
if (Input.GetKey(KeyCode.A))
{
//PlayerTransform.LookAt(Vector3.left);
PlayerTransform.Translate(Vector3.left * PlayerWalkSpeed);
}
if (Input.GetKey(KeyCode.D))
{
//PlayerTransform.LookAt(Vector3.right);
PlayerTransform.Translate(Vector3.right * PlayerWalkSpeed);
}
*/
if (Input.GetButton("Horizontal")) //检测虚拟按钮Horizontal,对应的绑定按键为d、a、小键盘右、小键盘左
{
//左右移动,Vector3坐标使用的是X轴!!
PlayerTransform.Translate(new Vector3(Input.GetAxis("Horizontal"), 0, 0) * PlayerWalkSpeed);
}
if (Input.GetButton("Vertical")) //检测虚拟按钮Vertical,对应的绑定按键为s、w、小键盘下、小键盘上
{
//上下移动,Vector3坐标使用的是Z轴!!
PlayerTransform.Translate(new Vector3(0, 0, Input.GetAxis("Vertical")) * PlayerWalkSpeed);
}
/* 暂时注释,为主角播放跳跃动画
if (Input.GetKeyDown(KeyCode.Space))
{
if (DHPlayVar == null)
{
print("主角异常:无法跳动,因为没有可用的动画对象");
}
else
{
//PlayerAnimation.Play("tiao2");
DHPlayVar.DHPlayFF("PlayerTiao");
}
}
*/
//主角跳起后不会着地--测试--InputManager练习2
if (Input.GetKey(KeyCode.Space))
{
PlayerTransform.Translate(Vector3.up * PlayerWalkSpeed);
}
//主角下沉--测试--InputManager练习2
if (Input.GetKey(KeyCode.X))
{
if (PlayerTransform.position.y >=0)
{
PlayerTransform.Translate(Vector3.down * PlayerWalkSpeed);
}
}
if (Input.GetMouseButton(0))
{
if (DHPlayVar == null && PlayerWeaponsAttackVar == null)
{
print("主角异常:无法攻击,因为没有可用的动画对象");
}
else
{
DHPlayVar.DHPlayFF("PlayerAttack");
Invoke("PlayerWeaponsAttackFF",0.6f);
}
}
}
//主角攻击武器启用方法
private void PlayerWeaponsAttackFF()
{
//启用游戏对象:GameObject.SetActive(true/false)
PlayerWeaponsAttackVar.SetActive(true);
DHPlayVar.DHPlayFF("PlayerWeaponsAttack");
//延迟调用主角攻击武器禁用方法
Invoke("PlayerWeaponsAttackDisable", 0.4f);
}
//主角攻击武器禁用方法
private void PlayerWeaponsAttackDisable()
{
//禁用游戏对象:GameObject.SetActive(false)
PlayerWeaponsAttackVar.SetActive(false);
}
}
|