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);
}
}
transform.Translate(...);
This method updates the player's position in each frame without considering the friction values set in the materials.transform.Translate(...)
) with a function that updates the player's position using physics, allowing friction to affect the player: rb.AddForce(moveDirection * moveSpeed);
private Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
}
// Draw the raycast for visualization
private void OnDrawGizmos()
{
Debug.DrawRay(transform.position - transform.up * 0.95f, transform.forward * 1f, Color.green);
}
public LayerMask groundLayerMask;
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);
}
}
Input.GetKeyDown(KeyCode.Space)
to detect if the player is pressing space.Debug.DrawRay
)rb.AddForce
, with ForceMode.Impulse
).