ブログ

CharacterControllerでオブジェクトに力を加える方法

(1)スクリプト

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

public class CharacterControllerPush : MonoBehaviour
{
    public float pushPower;

    private void OnControllerColliderHit(ControllerColliderHit hit)
    {
        Rigidbody rb = hit.collider.attachedRigidbody;

        if(!rb || rb.isKinematic)
        {
            return;
        }

        if(hit.moveDirection.y < -0.3f)
        {
            return;
        }

        Vector3 pushDir = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z);

        rb.velocity = pushDir * pushPower;
    }
}

(2)実行