-
-
Save I-himawari/b808281746b13cb9f5eec9dd0c1747eb to your computer and use it in GitHub Desktop.
【Unity】2D用の、キーボードで上下左右斜めに動かせるスクリプト
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using UnityEngine; | |
| using System.Collections; | |
| public class PlayerControlScript : MonoBehaviour { | |
| // 速度 | |
| public Vector2 SPEED = new Vector2(0.05f, 0.05f); | |
| // Use this for initialization | |
| void Start () { | |
| } | |
| // Update is called once per frame | |
| void Update () { | |
| // 移動処理 | |
| Move(); | |
| } | |
| // 移動関数 | |
| void Move(){ | |
| // 現在位置をPositionに代入 | |
| float moveX = 0f; | |
| float moveY = 0f; | |
| Vector2 Position = transform.position; | |
| // 左キーを押し続けていたら | |
| if(Input.GetKey("left")){ | |
| // 代入したPositionに対して加算減算を行う | |
| moveX -= SPEED.x; | |
| } else if(Input.GetKey("right")){ // 右キーを押し続けていたら | |
| // 代入したPositionに対して加算減算を行う | |
| moveX += SPEED.x; | |
| } | |
| if(Input.GetKey("up")){ // 上キーを押し続けていたら | |
| // 代入したPositionに対して加算減算を行う | |
| moveY += SPEED.y; | |
| } else if(Input.GetKey("down")){ // 下キーを押し続けていたら | |
| // 代入したPositionに対して加算減算を行う | |
| moveY -= SPEED.y; | |
| } | |
| if (moveX != 0f && moveY != 0f) { | |
| moveX /= 1.4f; | |
| moveY /= 1.4f; | |
| } | |
| Position.x += moveX; | |
| Position.y += moveY; | |
| // 現在の位置に加算減算を行ったPositionを代入する | |
| transform.position = Position; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment