LoginSignup
0

FarmRPG Unity PlayerBasics Part6 Movement 1/3 キーボード入力でオブジェクトが移動 InputとRigidBody.MovePositionを使う

Last updated at Posted at 2023-05-26

概要

今回はPlayerオブジェクトをwasd入力で動くようにします。
以下実装後の様子です。

dfasfdfddfasfdsadfsdfsa.gif

開発環境

IDE:Rider
Unity:2020.3.42(LTS)
OS:Windows10

UnityEditor上の設定

PlayerオブジェクトにRigidBodyとPlayerがアタッチされていることを確認します。

実装のポイント

キーボードの入力からC#の変数への変換ををUpgradeメソッド内で実行し、
RigidBodyの処理をfixedUpgradeメソッド内で行います。

image.png

斜め移動の係数は三角比を使って算出しています。
image.png

コード部分

Player

Player.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : SingletonMonobehaviour<Player>
{
    // Movement Parameters
    private float xInput;
    private float yInput;


    private Rigidbody2D rigidBody2D;
    private float movementSpeed;

    protected override void Awake()
    {
        base.Awake();
        rigidBody2D = GetComponent<Rigidbody2D>();
    }

    private void Update()
    {
        PlayerMovementInput();
    }
    
    private void FixedUpdate()
    {
        PlayerMovement();
    }

    private void PlayerMovement()
    {
        Vector2 move = new Vector2(xInput * movementSpeed * Time.deltaTime, yInput * movementSpeed * Time.deltaTime);
        rigidBody2D.MovePosition(rigidBody2D.position + move);
    }
    
    private void PlayerMovementInput()
    {
        // Get player input
        xInput = Input.GetAxisRaw("Horizontal");
        yInput = Input.GetAxisRaw("Vertical");

        // 斜め移動
        if (yInput != 0 && xInput != 0)
        {
            xInput = xInput * 0.71f;
            yInput = yInput * 0.71f;
        }

        // 一方向の移動
        if (xInput != 0 || yInput != 0)
        {
            movementSpeed = Settings.walkingSpeed;
        }
    }
    
}

Setting

Setting.cs
using UnityEngine;

public static class Settings 
{
    public const float walkingSpeed = 2.666f;
}

参考

C#

Unity Editor コンポーネント

Transform.positionとRigidBody.MovePositionの違い

transform.positionで動かすと物理判定が変になるとという程度の理解。(よくわかってない)

Unity スクリプト

Input.GetAxis

image.png

rigidBody.MovePosition

image.png

FixedUpdate

物理演算(座標移動)に使う

image.png

その他

Section5 12 Basic Player Movement

github コミット分(個人確認用 privateなので見れません)

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
What you can do with signing up
0