Kick-able Object (Unity c#)
A simple script you can use to make objects be “kicked” by your Player Character in Unity, with settings to adjust the behavior.
The object needs to have a Rigidbody and a BoxCollider Attached for the script to work.
In the Start() function the script automatically creates a box collider as trigger volume. This code can be easily optimized by removing this and manually adding a trigger volume to the object. But I want things simple and fool proof!
Example of thow the script might work on this cool skeleton we created!
Copy the code below and create a new class called MovedByPlayerMovement or download the file at the bottom of the page!
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(BoxCollider))] [RequireComponent(typeof(Rigidbody))] public class MovedByPlayerMovement : MonoBehaviour { [SerializeField] private float baseForce = 10f; [SerializeField] private float forceVariation = 5f; [SerializeField] private float directionVariation = 30f; [SerializeField] private float triggerVolumeSize = 1f; private const string PLAYERTAG = "Player"; private Rigidbody rb; private void Start() { if (rb == null) rb = GetComponent<Rigidbody>(); //Create a new BoxCollider to trigger the effect BoxCollider existingCollider = GetComponent<BoxCollider>(); if (existingCollider != null) { //Create a new Collider BoxCollider newCollider = gameObject.AddComponent<BoxCollider>(); //Center it at the original Collider and make the size bigger newCollider.center = existingCollider.center; newCollider.size = existingCollider.size * (1 + triggerVolumeSize); //Set it to trigger so OnTriggerEnter() triggers newCollider.isTrigger = true; } } private void OnTriggerEnter(Collider other) { // Check if the object collided with the player if (other.CompareTag(PLAYERTAG)) { Debug.Log("Hit by the player " + gameObject.name + ""); Vector3 playerVelocity = PlayerStateMachine.GetInstance().CharacterController.velocity; Vector3 launchDirection = playerVelocity.normalized; // Add random variation to the launch direction launchDirection = Quaternion.Euler( Random.Range(-directionVariation, directionVariation), Random.Range(5, directionVariation), //This ensures the object always moves UP Random.Range(-directionVariation, directionVariation) ) * launchDirection; // Calculate the force with some variation float forceMagnitude = baseForce + Random.Range(-forceVariation, forceVariation); Vector3 launchForce = launchDirection * forceMagnitude; // Apply the force and set the Rigidbody to be dynamic rb.isKinematic = false; rb.AddForce(launchForce, ForceMode.Impulse); } } }