天天看点

[Unity]实现按住WASD角色移动

using System.Collections;

using System.Collections.Generic;

using UnityEngine;



public class player_controller : MonoBehaviour

{

//用来设置移动速度

    public float speed;

//这里放三个不同的单词脚步声,然后我们在移动的时候随机播放其中之一

    public AudioSource[] 脚步音效;



       private void Update() {

//按住W

         if(Input.GetKey(KeyCode.W))

         {

                //改变人物朝向

                this.transform.eulerAngles=new Vector3(0,0,0);

               //使得角色持续移动

                this.transform.Translate(Vector3.forward*speed*Time.deltaTime);

                //移动的同时播放脚步声音

                if(!脚步音效[0].isPlaying&&!脚步音效[1].isPlaying&&!脚步音效[2].isPlaying)

                脚步音效[Random.Range(0,2)].Play();

         }else if(Input.GetKey(KeyCode.D))

         {

                this.transform.eulerAngles=new Vector3(0,270,0);

                this.transform.Translate(Vector3.forward*speed*Time.deltaTime);

                if(!脚步音效[0].isPlaying&&!脚步音效[1].isPlaying&&!脚步音效[2].isPlaying)

                脚步音效[Random.Range(0,2)].Play();

         }else if(Input.GetKey(KeyCode.A))

         {

                this.transform.eulerAngles=new Vector3(0,90,0);

                this.transform.Translate(Vector3.forward*speed*Time.deltaTime);

                if(!脚步音效[0].isPlaying&&!脚步音效[1].isPlaying&&!脚步音效[2].isPlaying)

                脚步音效[Random.Range(0,2)].Play();

         }else if(Input.GetKey(KeyCode.S))

         {

                this.transform.eulerAngles=new Vector3(0,180,0);

                this.transform.Translate(Vector3.forward*speed*Time.deltaTime);

                if(!脚步音效[0].isPlaying&&!脚步音效[1].isPlaying&&!脚步音效[2].isPlaying)

                脚步音效[Random.Range(0,2)].Play();

         }

    }

}

'''