昨天是中秋节,一家人出去玩了,没有进行学习,今天接着前天的继续学习我们的RPG游戏的开发,下一步我们要进行名称的输入和场景的切换。
public UIInput nameInput;
public void OnOkButtonClick(){
playerprefs.setInt("SelctedCharacterIndex",SelctedIndex);
playerprefs.setstring("name",nameInput);
//加载下一个场景
}
下一步,人物的行走控制,先实现定义标签,实例化点击效果,提升点击位置,将中加圆盘增加碰撞器,改变它的标签。
public class Tags : MonoBehaviour {
public const string ground = "Ground";
public const string player = "Player";
}
public class PlayerDirection : MonoBehaviour
{
public GameObject effect_click_prefab;
void Update ()
{
if (Input.GetMouseButtonDown (0)) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hitInfo;
bool isCollider = Physics.Raycast (ray,out hitInfo);
if (isCollider && hitInfo.collider.tag == Tags.ground) {
ShowClickEffect (hitInfo.point);
}
}
}
private void ShowClickEffect (Vector3 hitpoint)
{
Instantiate (effect_click_prefab, hitpoint, Quaternion.identity);
}
}
if (isMoving)//得到要移动的目标位置
{
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hitInfo;
bool isCollider = Physics.Raycast (ray, out hitInfo);
if (isCollider && hitInfo.collider.tag == Tags.ground) {
LookAtTarget (hitInfo.point);
}
}
void LookAtTarget (Vector3 hitPoint)//主角朝向目标位置
{
targetposition = hitPoint;
targetposition = new Vector3 (targetposition.x, transform.position.y, targetposition.z);
this.transform.LookAt (targetposition);
}
public class PlayerMove : MonoBehaviour {
public float Speed = 4.0f;
private PlayerDirection direction;
private CharacterController m_characterController;
// Use this for initialization
void Start () {
direction = this.GetComponent<PlayerDirection> ();
m_characterController = this.GetComponent<CharacterController> ();
}
// Update is called once per frame
void Update () {
float distance = Vector3.Distance (direction.targetposition, transform.position);
if(distance > 0.1f) {
m_characterController.SimpleMove (transform.forward * Speed);
}
}
}
下一步,是给角色加入了动画,先给角色导入动画,加上脚本
public class PlayerAnimation : MonoBehaviour {
private PlayerMove move;
private Animation m_animation;
// Use this for initialization
void Start () {
move = this.GetComponent<PlayerMove> ();
m_animation = this.GetComponent<Animation> ();
}
// Update is called once per frame
void LateUpdate () {
if(move.state == PlayerState.Moving) {
PlayAnim ("Run");
}
else if(move.state == PlayerState.Idle){
PlayAnim ("Idle");
}
}
void PlayAnim(string animName)
{
m_animation.CrossFade (animName);
}
}
脚本都写完,发现一个Bug,就是点击后,角色不是停在点击的位置,而是还是会往前面走,我们需要在行走脚本中,判断令其走或者不走,增加一个布尔类型的变量,并在Direction脚本中,随时更改角色的朝向。在视频中,并没有定义Animation组件,但是可以正常运行,我在脚本中却不行,因此我重新定义了m_Animation。