2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

プレイヤーを矢印キーで動かすスクリプト

Last updated at Posted at 2016-11-18
PlayerController.cs
using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour
{
    public Vector2 SPEED = new Vector2(0.05f, 0.05f);  //set speed line                                              

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        Move();

    }
    //when u push arrowkey

    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;
        Clamp();
    }
    void Clamp()
    {//プレイヤーをゲーム画面から出さないための範囲指定
        
        Vector2 min = Camera.main.ViewportToWorldPoint(new Vector2(0, 0));

       
        Vector2 max = Camera.main.ViewportToWorldPoint(new Vector2(1, 1));

        Vector2 pos = transform.position;

        
        pos.x = Mathf.Clamp(pos.x, min.x, max.x);
        pos.y = Mathf.Clamp(pos.y, min.y, max.y);

        transform.position = pos;
    }
}
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?