Unityでボーリングゲームを作る #1 玉を投げる

投稿者: | 2020-01-20

Unityでボーリングゲームを作ります。

スタンダードアセットのFPSコントローラから玉を投げます。プレイヤーの進む方向へ、プレイヤーが早く動いているほど強く玉を投げてみます。

玉のプレハブを作ります。

コライダーのRigidbody、「Ball」レイヤーを付けておきます。

FPSコントローラをシーンに配置して、ルートのオブジェクトに「Player」レイヤーを付けます。

子オブジェクトのFirstPersonCharacterに、玉を投げるためのスクリプトを付けました。

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

public class BowlingScript : MonoBehaviour
{
    public GameObject ball;
    Rigidbody rb_ball;
    public float power = 3f;

    CharacterController cc_player;

    // Start is called before the first frame update
    void Start()
    {
        rb_ball = ball.GetComponent<Rigidbody>();
        cc_player = transform.root.gameObject.GetComponent<CharacterController>();
    }

    // Update is called once per frame
    void Update()
    {

        if (Input.GetMouseButtonDown(0)) // マウスの左クリックをしたとき
        {
            Vector3 arm = transform.position;
            arm.y -= 1;

            rb_ball = Instantiate(ball, arm, transform.rotation).GetComponent<Rigidbody>(); // 玉を生成
            rb_ball.AddForce(cc_player.velocity * power + transform.forward, ForceMode.Impulse); // プレイヤーの前方へ力を加える
        }

    }

}

transform.positionはプレイヤーの頭の位置なので、Y座標を少し下げています。
玉を作ってAddForceでプレイヤーの動いている方向へ力を加えます。
FPSコントローラはキャラクターコントローラーコンポーネントを使って動かすので、プレイヤーの速度を得るには、CharacterController.velocity を使います。立ち止まっているときもちょっと玉を転がしたいので、transform.forwardを足してみました。

コメントを残す

メールアドレスが公開されることはありません。