dev-notes/dotnet/unity/collisions.md

82 lines
2.3 KiB
Markdown
Raw Normal View History

2021-01-31 11:05:37 +01:00
# Collisions (Physics)
## Rigidbody Component
2021-09-20 19:35:32 +02:00
Enables physics on the game objects.
2021-01-31 11:05:37 +01:00
Rigidbodies collide with other objects instead of going through them.
2021-09-20 19:35:32 +02:00
Avoid object rotation on collisions:
2021-01-31 11:05:37 +01:00
1. Assign `Rigidbody` component to object
2021-09-20 19:35:32 +02:00
2. Enable Freeze Rotation in Rigidbody > Constraints
2021-01-31 11:05:37 +01:00
```cs
using UnityEngine;
using System.Collections;
public class GameObject : MonoBehaviour {
Rigidbody = rigidbody; // game object rigidbody reference container
void Start()
{
2021-09-20 19:35:32 +02:00
rigidbody = GetComponent<Rigidbody>(); // get rigidbody reference
2021-01-31 11:05:37 +01:00
}
void Update()
{
}
2021-09-20 19:35:32 +02:00
// FixedUpdate is calls every x seconds (not influenced by FPS instability)
// used for physics calculations which should be FPS independent
2021-01-31 11:05:37 +01:00
void FixedUpdate()
{
Time.fixedDeltaTime; // fixed amount of time
2021-09-20 19:35:32 +02:00
Time.timeDelta; // if called inside FIxedUpdate() behaves like fixedDeltaTime
2021-01-31 11:05:37 +01:00
}
}
```
## Box Collider Component
Enable `Is Trigger` to register the collision but avoid blocking the movement of the objects.
The trigger can generate a event to signal the contact with the object.
2021-09-20 19:35:32 +02:00
One of the colliding GameObjects *must have* the `Rigidbody` component and the other `Is Trigger` enabled.
To detect the collision but avoid computing the physics `Is Kinematic` must be enabled in the `Rigidbody` component.
2021-01-31 11:05:37 +01:00
```cs
using UnityEngine;
using System.Collections;
public class GameObject : MonoBehaviour {
Rigidbody = rigidbody; // game object rigidbody reference container
void Start()
{
2021-09-20 19:35:32 +02:00
rigidbody = GetComponent<Rigidbody>(); // get rigidbody reference
2021-01-31 11:05:37 +01:00
}
2021-09-20 19:35:32 +02:00
// FixedUpdate is calls every x seconds (not influenced by FPS instability)
// used for physics calculations which should be FPS independent
2021-01-31 11:05:37 +01:00
void FixedUpdate()
{
Time.fixedDeltaTime; // fixed amount of time
2021-09-20 19:35:32 +02:00
Time.timeDelta; // if called inside FixedUpdate() behaves like fixedDeltaTime
2021-01-31 11:05:37 +01:00
}
// called on box collision.
void OnTriggerEnter(Collider triggerCollider) {
2021-09-20 19:35:32 +02:00
// detect a collision with a particular GameObject(must have a TAG)
2021-01-31 11:05:37 +01:00
if (triggerCollider.tag = "tag") {
Destroy(triggerCollider.gameObject); // destroy tagged item on collision
//or
Destroy(gameObject); // destroy itself
}
}
```