はりうすブログ (のすけのメモ)

湘南にある小さな会社 代表 ”のすけ”のブログです

【Unity道場6】プレイヤーを動かすPlayerコントローラーの作成

回答例

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
  public float speed = 3f;  //移動スピード

  // Start is called before the first frame update
  void Start()
  {

  }

  // Update is called once per frame
  void Update()
  {
    float x = Input.GetAxis("Horizontal");  //左右方向のキー取得
    float z = Input.GetAxis("Vertical"); //上下方向のキー取得

    float addX = speed * x * Time.deltaTime;
    float addZ = speed * z * Time.deltaTime;

    transform.GetComponent<Rigidbody>().MovePosition(transform.position + new Vector3(addX, 0, addZ));
    transform.LookAt(transform.position + new Vector3(addX, 0, addZ));
  }
}