Rename all file to kebab-case

This commit is contained in:
Marcello 2022-05-13 18:33:39 +02:00
parent ffc085d78a
commit 68ca4e4f86
117 changed files with 0 additions and 1260 deletions

View file

@ -0,0 +1,81 @@
# Collisions (Physics)
## Rigidbody Component
Enables physics on the game objects.
Rigidbodies collide with other objects instead of going through them.
Avoid object rotation on collisions:
1. Assign `Rigidbody` component to object
2. Enable Freeze Rotation in Rigidbody > Constraints
```cs
using UnityEngine;
using System.Collections;
public class GameObject : MonoBehaviour {
Rigidbody = rigidbody; // game object rigidbody reference container
void Start()
{
rigidbody = GetComponent<Rigidbody>(); // get rigidbody reference
}
void Update()
{
}
// FixedUpdate is calls every x seconds (not influenced by FPS instability)
// used for physics calculations which should be FPS independent
void FixedUpdate()
{
Time.fixedDeltaTime; // fixed amount of time
Time.timeDelta; // if called inside FIxedUpdate() behaves like fixedDeltaTime
}
}
```
## 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.
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.
```cs
using UnityEngine;
using System.Collections;
public class GameObject : MonoBehaviour {
Rigidbody = rigidbody; // game object rigidbody reference container
void Start()
{
rigidbody = GetComponent<Rigidbody>(); // get rigidbody reference
}
// FixedUpdate is calls every x seconds (not influenced by FPS instability)
// used for physics calculations which should be FPS independent
void FixedUpdate()
{
Time.fixedDeltaTime; // fixed amount of time
Time.timeDelta; // if called inside FixedUpdate() behaves like fixedDeltaTime
}
// called on box collision.
void OnTriggerEnter(Collider triggerCollider) {
// detect a collision with a particular GameObject(must have a TAG)
if (triggerCollider.tag = "tag") {
Destroy(triggerCollider.gameObject); // destroy tagged item on collision
//or
Destroy(gameObject); // destroy itself
}
}
```

View file

@ -0,0 +1,30 @@
# Coroutines
[Coroutines - Unity manual](https://docs.unity3d.com/Manual/Coroutines.html)
When you call a function, it runs to completion before returning. This effectively means that any action taking place in a function must happen *within a single frame update*; a function call can't be used to contain a procedural animation or a sequence of events over time.
A coroutine is like a function that has the ability to pause execution and return control to Unity but then to continue where it left off on the following frame.
It is essentially a function declared with a return type of IEnumerator and with the yield return statement included somewhere in the body. The `yield return null` line is the point at which execution will pause and be resumed the following frame.
```cs
//coroutine
IEnumerator coroutine()
{
// action performed
yield return null; // pause until next iteration
// or
// By default, a coroutine is resumed on the frame after it yields but it is also possible to introduce a time delay
yield return new WaitForSeconds(seconds); // wait seconds before resuming
// or
yeld return StartCoroutine(coroutine()); // wait for another coroutine to finish before starting
}
StartCoroutine(coroutine()); // start the coroutine
StopCoroutine(coroutine()); // stop the coroutine
```

View file

@ -0,0 +1,81 @@
# Input Manager
The Input Manager uses the following types of controls:
- **Key** refers to any key on a physical keyboard, such as `W`, `Shift`, or the `space bar`.
- **Button** refers to any button on a physical controller (for example, gamepads), such as the `X` button on an Xbox One controller.
- A **virtual axis** (plural: axes) is mapped to a **control**, such as a button or a key. When the user activates the control, the axis receives a value in the range of `[-1..1]`.
## Virtual axes
### Axis Properties
**Name**: Axis name. You can use this to access the axis from scripts.
**Negative Button**, **Positive Button**: The controls to push the axis in the negative and positive direction respectively. These can be keys on a keyboard, or buttons on a joystick or mouse.
**Alt Negative Button**, **Alt Positive Button**: Alternative controls to push the axis in the negative and positive direction respectively.
**Gravity**: Speed in units per second that the axis falls toward neutral when no input is present.
**Dead**: How far the user needs to move an analog stick before your application registers the movement. At runtime, input from all analog devices that falls within this range will be considered null.
**Sensitivity**: Speed in units per second that the axis will move toward the target value. This is for digital devices only.
**Snap**: If enabled, the axis value will reset to zero when pressing a button that corresponds to the opposite direction.
**Type**: The type of input that controls the axis. Select from these values:
- Key or Mouse button
- Mouse Movement
- Joystick Axis
**Axis**: The axis of a connected device that controls this axis.
**JoyNum**: The connected Joystick that controls this axis. You can select a specific joystick, or query input from all joysticks.
### Axis Values
Axis values can be:
- Between `-1` and `1` for joystick and keyboard input. The neutral position for these axes is `0`. Some types of controls, such as buttons on a keyboard, aren't sensitive to input intensity, so they can't produce values other than `-1`, `0`, or `1`.
- Mouse delta (how much the mouse has moved during the last frame) for mouse input. The values for mouse input axes can be larger than `1` or smaller than `-1` when the user moves the mouse quickly.
```cs
//Define the speed at which the object moves.
float moveSpeed = 10;
//Get the value of the Horizontal input axis.
float horizontalInput = Input.GetAxis("Horizontal");
//Get the value of the Vertical input axis.
float verticalInput = Input.GetAxis("Vertical");
Vector3 direction = new Vector3(horizontalInput, 0, verticalInput).normalized;
Vector3 velocity = direction * moveSpeed;
//Move the object to XYZ coordinates defined as horizontalInput, 0, and verticalInput respectively.
transform.Translate(velocity * Time.deltaTime);
```
[Time.deltaTime][dt] represents the time that passed since the last frame. Multiplying the moveSpeed variable by Time.deltaTime ensures that the GameObject moves at a constant speed every frame.
[dt]: https://docs.unity3d.com/ScriptReference/Time-deltaTime.html
`GetAxis`: returns the value of the virtual axis identified.
`GetAxisRaw`: returns the value of the virtual axis identified with no smoothing filtering applied.
## Keys
**Letter keys**: `a`, `b`, `c`, ...
**Number keys**: `1`, `2`, `3`, ...
**Arrow keys**: `up`, `down`, `left`, `right`
**Numpad keys**: `[1]`, `[2]`, `[3]`, `[+]`, `[equals]`, ...
**Modifier keys**: `right shift`, `left shift`, `right ctrl`, `left ctrl`, `right alt`, `left alt`, `right cmd`, `left cmd`
**Special keys**: `backspace`, `tab`, `return`, `escape`, `space`, `delete`, `enter`, `insert`, `home`, `end`, `page up`, `page down`
**Function keys**: `f1`, `f2`, `f3`, ...
**Mouse buttons**: `mouse 0`, `mouse 1`, `mouse 2`, ...
**Specific button on *any* joystick**: `joystick button 0`, `joystick button 1`, `joystick button 2`, ...
**specific button on a *specific* joystick**: `joystick 1 button 0`, `joystick 1 button 1`, `joystick 2 button 0`, ...
```cs
Input.GetKey("a");
Input.GetKey(KeyCode.A);
```
[Input.GetKey](https://docs.unity3d.com/ScriptReference/Input.GetKey.html)
[KeyCode](https://docs.unity3d.com/ScriptReference/KeyCode.html)

View file

@ -0,0 +1,14 @@
# Prefabs
Prefabs are a blueprint for GameObjects and any change made to the prefab is inherited by all it's instances.
## Script Instantiation
```cs
public GameObject prefab; // reference to the prefab
// instantiate a game GameObject from the prefab with specified position and rotation (rotation must be a quaternion)
GameObject newInstance = (GameObject) Instantiate(prefab, positionVector3, Quaternion.Euler(rotationVector3)); // instantiate prefab and get reference to instance
// Instance returns a object and since a GameObject was passed to Instantiate() the returned object can be casted to a GameObject
```

View file

@ -0,0 +1,83 @@
# Raycasting Notes
A raycast is conceptually like a laser beam that is fired from a point in space along a particular direction. Any object making contact with the beam can be detected and reported.
## 3D Raycasting
```cs
void Update()
{
// constructor takes in a position end direction
Ray ray = new Ray(transform,position, transform.forward);
RaycastHit hitInfo; // struct, stores data on ray collision
hitInfo.distance // distance from origin to collision point
hitInfo.collider // collider of the hit object
hitInfo.transform // transform og the hit object
hitInfo.collider.gameObject // reference to the object hit by the ray
hitInfo.collider.gameObject // reference to the object hit by the ray
hitInfo.normal // normal vector og the hit surface
hitInfo.point // actual point of collision
// static method, object must have a collider dot the collision to happen, returns a BOOL
Physics.Raycast(ray, out hitInfo); // update hitInfo based on ray collisions
Physics.Raycast(ray, out hitInfo, float maxRayDistance); // limit the ray length
Physics.Raycast(ray, out hitInfo, Mask mask); // specify with which layers the ray can interact, layer must be applied to object's mask
Physics.Raycast(ray, out hitInfo, Mask mask, QueryTriggerInteraction.Ignore); // ignore collision if "is trigger" is enabled on other objects
// detect a collision
if (Physics.Raycast(ray, out hitInfo))
{
//collision happened
// draw the ray in game for debugging
Debug.DrawLine(ray.origin, hitInfo.point, Color.red); // draw red line if collision happens
}
else
{
Debug.DrawLine(ray.origin, ray.origin + ray.direction * 100, Color.blue); // draw blue line if collision happens, arrival point is 100 units from the origin since the ray goes to infinity
}
}
```
### Detect mouse pointed point in-game
```cs
public Camera gameCamera;
void Update()
{
// ray going from camera through a screen point
Ray ray = gameCamera.ScreenPointToRay(Input.mousePosition); // Input.mousePosition is the position of the mouse in pixels (screen points)
RaycastHit hitInfo; // place pointed by the mouse
Physics.Raycast(ray, out hitInfo) // update pointed position
}
```
## 2D Raycasting
```cs
void Start()
{
Physics2D.queriesStartColliders = false; // avoid collision with collider of the ray generator gameObject
}
void Update()
{
// returns a RaycastHit2D, needs an origin and direction separately
Raycast2D hitInfo = Physics2D.Raycast(Vector2 origin, Vector2 direction);
Raycast2D hitInfo = Physics2D.Raycast(Vector2 origin, Vector2 direction, float maxRayDistance);
Raycast2D hitInfo = Physics2D.Raycast(Vector2 origin, Vector2 direction, float maxRayDistance);
Raycast2D hitInfo = Physics2D.Raycast(Vector2 origin, Vector2 direction, float minDepth, float maxDepth); // set range of z-coord values in which detect hits (sprites depth)
//! the ray starts from INSIDE the gameObject and can collider with it's collider
// detect collision
if (hitInfo.collider != null) {
// collision happened
Debug.DrawLine(transform.position, hitInfo.point)
}
}
```

135
dotnet/unity/scripting.md Normal file
View file

@ -0,0 +1,135 @@
# Unity C# Scripting
## Logging
```c#
Debug.Log(string); //output message to console (more powerful and flexible than print())
Print(string); //output message to console
```
## Scripts
```c#
public class ClassName : MonoBehaviour {
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Time.deltaTime; // time since last frame
}
// FixedUpdate is calls every x seconds (not influenced by FPS instability)
// used for physics calculations which should be FPS independent
void FixedUpdate()
{
Time.fixedDeltaTime; // fixed amount of time
Time.timeDelta; // if called inside FIxedUpdate() behaves like fixedDeltaTime
}
}
```
### Script communication
Referencing data in a script from another.
```cs
//example of a script to be referenced in another
Using System;
public class Player : MonoBehaviour {
public float health = 10;
public event Action OnPlayerDeath; //event of type Action, needs using System
void Start() {
}
void Update() {
if (health <= 0) {
if (OnPlayerDeath != null) {
OnPlayerDeath(); // invoke Action (if no subscribers event will be NULL, can cause errors)
}
Destroy(GameObject); // needs to be notified
}
}
}
```
```cs
// example of script needing a reference to another
public class GameUI : MonoBehaviour {
Player player; //instance of referenced GameObject to be found by its type
void Start(){
GameObject playerObj = GameObject.Find("Player"); //reference to game object
GameObject playerObj = GameObject.FindGameObjectWithTag("Tag"); //reference to game object
player = playerObj.GetComponent<Player>(); // get script attached to the GameObject
player = FindObjectOfType<Player>(); // get reference to an object
// on event invocation all subscriber methods will be called
player.OnPlayerDeath += GameOver; // subscribe method to event
}
void Update() {
DrawHealthBar(plyer.health); // call method passing data of player GameObject
}
void DrawHealthBar(float playerHealth) {
// implementation
}
public void GameOver() {
//game over screen
}
}
```
## Screen
### 2D Screen Measures
Aspect Ratio = `(screen_width [px]) / (screen_height [px])`
Orthographic Size `[world units]` = `(screen_height [world units] / 2)`
Aspect Ratio * Orthographic Size = `(screen_width [world units] / 2)`
Screen Width `[world units]` = `(AspectRatio * OrthographicSize * 2)`
```cs
screenWidth = Camera.main.aspect * Camera.main.orthographicSize * 2;
```
## Scriptable Objects
Class to store data in stand alone assets, used to keep data out of scripts.
Can be used as a template.
```c#
[CreateAssetMenu(menuName = "ScriptableObjectName")] //enable creation of scriptable object
public class ScriptableObjectName : ScriptableObject {
//data structure here
}
```
### Game Object Serialization
```c#
[SerializeField] type variable; //access game object from code
```
### Game Object Data Access
```c#
public type GetVariable(){
return variable;
}
```

View file

@ -0,0 +1,87 @@
# Vector, Transform, Space
## Vector2, Vector3, Vector4
[Vector3 Docs](https://docs.unity3d.com/ScriptReference/Vector3.html)
Used to store positions, velocities and directions.
Magnitude = `sqrt(Math.pow(x, 2) + Math.pow(y, 2))`
Direction = `(x / Magnitude, y / Magnitude)`
The direction is calculated by normalizing the vector to make it become a unit vector (*versor*).
```cs
Vector3.x // x coord of vector
Vector3.y // x coord of vector
Vector3.z // x coord of vector
Vector3.magnitude
Vector3.normalized
Vector3.up // Vector3(0, 1, 0)
Vector3.down // Vector3(0, -1, 0)
Vector3.left // Vector3(-1, 0, 0)
Vector3.right // Vector3(1, 0, 0)
Vector3.forward // Vector3(0, 0, 1)
Vector3.back // Vector3(0, 0, -1)
Vector3.one // Vector3(1, 1, 1)
Vector3.zero // Vector3(0, 0, 0)
Vector3.one // Vector3(1, 1, 1)
```
### Operations
```cs
Vector3(x, y, z) * n = Vector3(xn, yn, yz);
Vector3(x, y, z) / n = Vector3(x / n, y / n, y / z);
Vector3(x1, y1, z1) + Vector3(x2, y2, z2) = Vector3(x1 + x2, y1 + y2, z1 + z2);
Vector3(x1, y1, z1) - Vector3(x2, y2, z2) = Vector3(x1 - x2, y1 - y2, z1 - z2);
Quaternion.Euler(Vector3) // convert a Vector3 to a Quaternion
```
### Movement
Speed = value m/s
Velocity = Direction * Speed
MovementInFrame = Speed * timeSinceLastFrame
## Transform
[Transform Docs](https://docs.unity3d.com/ScriptReference/Transform.html)
```cs
// properties
transform.position // Vector3 - global position
transform.localPosition // Vector3 - local position
transform.rotation // Quaternion - global rotation
transform.parent // Transform - parent of the object
transform.localScale = Vector3; // set object dimensions
// methods
transform.Rotate(Vector3 * Time.deltaTime * speed, Space); // set rotation using vectors in selected space (Space.Self or Space.World)
transform.Translate(Vector3 * Time.deltaTime * speed, Space); // set movement in selected space
```
### Local, GLobal & Object Space
**Local Space**: Applies transformation relative to the *local* coordinate system (`Space.Self`).
**Global Space**: Applies transformation relative to the *world* coordinate system (`Space.World`)
### Parenting
Changing the parent will make position, scale and rotation of the child object relative to the parent but keep the world space's position, rotation and scale the same.
Setting the parentele by script:
```cs
public class ParentScript : MonoBehaviour {
public Transform childTransform; // reference to the child object transform
childTransform.parent = transform; // when evaluated at runtime sets current object as parent of another
}
```