概要
今回はPlayerオブジェクトをwasd入力で動くようにします。
以下実装後の様子です。
開発環境
IDE:Rider
Unity:2020.3.42(LTS)
OS:Windows10
UnityEditor上の設定
PlayerオブジェクトにRigidBodyとPlayerがアタッチされていることを確認します。
実装のポイント
キーボードの入力からC#の変数への変換ををUpgradeメソッド内で実行し、
RigidBodyの処理をfixedUpgradeメソッド内で行います。
コード部分
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
rigidBody.MovePosition
FixedUpdate
物理演算(座標移動)に使う
その他
Section5 12 Basic Player Movement
github コミット分(個人確認用 privateなので見れません)