Skip to content

Instantly share code, notes, and snippets.

@Buravo46
Last active December 18, 2022 12:22
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Buravo46/7728812 to your computer and use it in GitHub Desktop.
Save Buravo46/7728812 to your computer and use it in GitHub Desktop.
【Unity】2D用の、キーボードで上下左右動かせるスクリプト
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に代入
Vector2 Position = transform.position;
// 左キーを押し続けていたら
if(Input.GetKey("left")){
// 代入したPositionに対して加算減算を行う
Position.x -= SPEED.x;
} else if(Input.GetKey("right")){ // 右キーを押し続けていたら
// 代入したPositionに対して加算減算を行う
Position.x += SPEED.x;
} else if(Input.GetKey("up")){ // 上キーを押し続けていたら
// 代入したPositionに対して加算減算を行う
Position.y += SPEED.y;
} else if(Input.GetKey("down")){ // 下キーを押し続けていたら
// 代入したPositionに対して加算減算を行う
Position.y -= SPEED.y;
}
// 現在の位置に加算減算を行ったPositionを代入する
transform.position = Position;
}
}
#pragma strict
// 速度
var SPEED:Vector2 = Vector2(0.05f, 0.05f);
// Use this for initialization
function Start () {
}
// Update is called once per frame
function Update () {
// 移動処理
Move();
}
// 移動関数
function Move(){
// 左キーを押し続けていたら
if(Input.GetKey("left")){
// 代入したPositionに対して加算減算を行う
transform.position.x -= SPEED.x;
} else if(Input.GetKey("right")){ // 右キーを押し続けていたら
// 代入したPositionに対して加算減算を行う
transform.position.x += SPEED.x;
} else if(Input.GetKey("up")){ // 上キーを押し続けていたら
// 代入したPositionに対して加算減算を行う
transform.position.y += SPEED.y;
} else if(Input.GetKey("down")){ // 下キーを押し続けていたら
// 代入したPositionに対して加算減算を行う
transform.position.y -= SPEED.y;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment