6. Physics: forces and materials

Wall explosion (forces)

using UnityEngine;

public class BarrelTriggerController : MonoBehaviour
{
    public float explosionForce = 180f;

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("ExplosiveBarrel"))
        {
            ExplodeBarrel(other.gameObject);
        }
    }

    private void ExplodeBarrel(GameObject barrel)
    {
        Debug.Log("boom");

        // Get all Rigidbody components in children (pieces of the wall)
        Rigidbody[] rigidbodies = GetComponentsInChildren<Rigidbody>();

        foreach (Rigidbody rb in rigidbodies)
        {
            // Enable physics simulation
            rb.isKinematic = false;

            // Calculate the direction away from the explosion point
            Vector3 explosionDirection = rb.transform.position - barrel.transform.position;

            // Apply force to each Rigidbody piece
            rb.AddForce(explosionDirection.normalized * explosionForce / (explosionDirection.magnitude*explosionDirection.magnitude), ForceMode.Impulse);
        }

        Destroy(barrel);
    }
}

Sand and ice (physics materials)

    private Rigidbody rb;

    private void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

Player controller fix (physics-based movement)

    // Draw the raycast for visualization
    private void OnDrawGizmos()
    {
        Debug.DrawRay(transform.position - transform.up * 0.95f, transform.forward * 1f, Color.green);
    }

    void FixedUpdate()
    {
        // Update player position
        rb.AddForce(moveDirection * moveSpeed);

        // Raycast forward to detect ground in front of the player's feet
        if (Physics.Raycast(transform.position - transform.up * 0.95f, transform.forward, 1f, groundLayerMask))
        {
            // Add upward force to help the player ascend
            rb.AddForce(Vector3.up * moveSpeed*0.4f);
        }

        // Rotate the player to face the crosshair
        Vector3 lookDirection = crosshair.position - transform.position;
        lookDirection.y = 0f; // Ensure the player doesn't tilt up or down
        if (lookDirection != Vector3.zero)
        {
            Quaternion targetRotation = Quaternion.LookRotation(lookDirection);
            transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, Time.fixedDeltaTime * rotateSpeed);
        }
    }

Jumping

< ^ >