ラケットの作成
壁やボールと同じようにゲームオブジェクトを生成します
Hierarchy内で右クリック > 3D Object > Cube を選択します

作成したCubeを選択し、名前を「Racket」に変更
Transformを下記の画像のように設定します

Rigidbodyの追加・設定
ボールと同様にRigitbodyを追加します
Racketを選択 > Inspector内のAddComponent > Rigidbodyを選択
Rigidbody内は下記の画像のように設定

スクリプトの設定
ここではキーボードの「←」「→」キーで、ラケットを動かす機能を実装していきます
Racketを選択 > Add Component > New script > Name に「Racket」を入力
Assets内に下記のRacketが生成されたらダブルクリックで開いてください

コードは下記の内容を記述してください
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Racket : MonoBehaviour
{
//力の大きさ
private float accel = 500.0f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
this.GetComponent<Rigidbody>()
.AddForce(
transform.right * Input.GetAxisRaw("Horizontal") * accel,ForceMode.Impulse
);
}
}
コードの内容をざっくり記述します
private float accel = 500.0f;
今回、Racketは力を加えて動かしますが、その大きさを定義します
this.GetComponent<Rigidbody>()
.AddForce(
transform.right * Input.GetAxisRaw("Horizontal") * accel,ForceMode.Impulse
);
this.GetComponent<Rigidbody>()でこのスクリプトが割り当てられているRigidbody、つまり「Racket」を取得しています
それに対してAddForeceで力を加えています
AddForceの引数は
transform.rightはx軸方向
Input.GetAxisRaw(“Horizontal”)は「←」「→」キーの入力の取得
を意味しています
以上を記述して保存をすると完成です!
実装の確認
実装の確認をします
上の再生ボタンをクリックし、ゲームを再生してください

下記のように「←」「→」キーの入力でラケットが動けば成功です

だいぶブロック崩しっぽくなってきましたね
まとめ
今回はブロック崩しのラケット機能を実装しました
次回はブロックの配置とボールとの当たり判定で消す機能を追加していきます
コメント