作成したオブジェクトに初速を与える

ブロック崩しなどで、ゲーム開始時にボールを動かすための「Sprict」です。

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

public class BallController : MonoBehaviour

{
    public float speed = 10;

    // Start is called before the first frame update
    private void Start()
    {
        var force = ( transform.forward + transform.right ) * speed;
        GetComponent<Rigidbody>().AddForce(force, ForceMode.VelocityChange);
    }

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

動かす物体の速度を設定

public float speed = 10;

AddForce関数を使った移動

var force = ( transform.forward + transform.right ) * speed;

GetComponent<Rigidbody>().AddForce(force, ForceMode.VelocityChange);

「var force」で「var」の変数名を「force」と命名しています。

2段目は「AddForce」関数を利用して移動の設定を行っています。






参考にしたサイトが「var force」(varは例外的にどんな型でも入る変数)を使っているのですが、今回は「( transform.forward + transform.right ) * speed」と変数が3つなので「Vector3」で組んだ方が処理速度が速くなるかもです。

この辺りの開設は「Unityプログラミング基礎 (変数からclassまで)」で詳しく解説されてるので、そちらを参考にしてみたいと思います。

Unityプログラミング基礎 (変数からclassまで)