0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Unity使ってゲームを作ってみる その1 プレイヤーの左右移動

Last updated at Posted at 2025-02-27

はじめに

仕事が終わった後、何かコードが書きたくなり...
なんとなく興味のあったゲーム制作(未経験)を始めてみることに

とりあえず簡単な処理を書いて、プレイヤーを動かしてみる
素人なのでお粗末な内容でも足からず...

プレイヤーの左右移動の実装

プレイヤーを A/Dキー(←→キー) で 左右に移動 させる機能を実装する

手順

  1. プレイヤー(四角い図形)を作成
  2. A/Dキー(←→キー)の入力を取得するコードを書く
  3. コードをPlayerにアタッチ
  4. 動作確認

1. プレイヤー(四角い図形)を作成

スクリーンショット 2025-02-28 1.29.40.png

2D Object から Square を選択し、プレイヤーとして配置

スクリーンショット 2025-02-28 1.34.22.png

この白い四角がPlayer

2. A/Dキー(←→キー)の入力を取得するコードを書く

キー入力を検知して、プレイヤーを移動させるスクリプトを作成

Player.cs
using UnityEngine;

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

  // フレームごとに発火する
  void Update() {
    // A/Dキー or ←→キー
    float move = Input.GetAxis("Horizontal");
    // キャラクターの移動
    transform.position += new Vector3(move * speed * Time.deltaTime, 0, 0);
  }
}
  • Update()
    • 毎フレーム実行 される(60FPSなら1秒間に60回)
  • Input.GetAxis("Horizontal")
    • Aキー or ←キー を押すと -1、Dキー or →キー を押すと 1 を取得
  • Time.deltaTime
    • フレームレートに依存せず一定速度で移動

3. コードをPlayerにアタッチ

作成したスクリプト Player.cs を Player オブジェクトにアタッチ

スクリーンショット 2025-02-28 1.39.44.png

4. 動作確認

move.gif

speedをいじると移動速度も変わる

move2.gif

はい、とりあえず動かせました
これで、プレイヤーの左右移動の実装完了

また機能を追加したらまとめます!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?