Tenta Flashcards

1
Q

Gravity only operates along a fixed world vector. How could you simulate a planet orbiting the sun?

A

Rotate the GameObject by obtaining
- The position of the sun
- The axis of rotation
- Angular speed

then
transform.RotateAround(sun.position, Vector3.up, orbitspeed * Time.DeltaTime)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the code for orbiting a planet around the sun?

A

public Transform sun;
public float orbitSpeed;
void Update{
transform.RotateAround(sun.position, Vector3.up, orbitspeed*Time.DeltaTime); }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How can we add a star orbiting the planet that’s orbiting the sun?

A

GameObject star;
star.transform.RotateAround(transform.position, vector3.up, orbitSpeed*Time.DeltaTime);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How can we use state machines to structure game logic?

A

It organises game logic into different states, each with specific behaviours. Transitions between states are managed systematically -> Improving code clarity and scalability. Use switch cases
enum GameState {MainMenu, Playing, Paused)
GameState currState = GameState.MainMenu

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How does the garbage collection in unity work?

A

When the managed heap fills up, meaning that there isn’t a space big enough for a new allocation of data, the garbage collector will run to try to make room for it.

When this happens, Unity will examine the heap, and remove any old data that no longer has any references to it.

Then if, after running the garbage collector, there still isn’t a space big enough for the data allocation, the heap will expand to make more room.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How can you write low garbage code in unity?

A
  • Use object pooling to avoid frequent instantiation and destruction of objects
  • Avoid allocating memory in performance-critical methods like Update()
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How would you display (and update) a score on the screen while a game is being played, using the unity GUI?

A
  • Add text (or TextMeshPro) to canvas
  • Get references to the text objects in the code

public TextMeshPro scoreText;
public int score;

public void addScore (int points){
score += points;
scoreText.text = “Score: “ + score.ToString(); }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Explain Mark And Sweep

A

Mark: Start from the root/global references and recursively visit all reachable objects, marking the accessible

Sweep: Pass through “all” objects and delete those not marked as accessible

No other processing can be done which leads to frame rate drop
(Try to minimise GC calls)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How can we determine if zombie can see the player?

A

float dot = Vector3.dot(vec1,vec2)
1. Obtain the normalised vector
a) Zombie facing direction
Zombie.transform.forward
b) Direction from zombie to player
Vector3 diff = p1-p2
Vector3 dir = diff.normalised
2. If dot of a) and b) is greater than 0 -> the zombie can see the player

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Explain ScreenSpace: Overlay and ScreenSpace: Camera

A

Overlay: Canvas scaled to fit and then rendered without reference to the scene or camera (always drawn over other graphics)

Camera: Rendered as a plane A DISTANCE from the camera (objects will be rendered over it)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How can you spawn sparks using the parameters of a collision?

A

(In OnCollisionEnter)
for int i in collision.contacts.length{
ContactPoint cp = collision.contacts[i]
GameObject go = Instantiate(GameManager.instance, sparkEmitterPrefab)
go.transform.position = cp.point;
go.transform.LookAt(cp.point+cp.normal)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is a coroutine in Unity?

A

Special functions that can pause their execution (not threads). When they are activated, they will execute up until the next yield statement and then pause until it’s resumed.

Good for:
-Making things happen step-by-step
-Writing routines that happen over time
- Wrirting routines that have to wait for another operation to finish

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Explain colliders, triggers and rigidbodys

A

Collider components define the shape of an object for the purposes of physical collisions.

Colliders and rigidbodies will physically respons to impacts

Triggers will not not. Triggers enable game-logic interaction when you don’t want physical collision responses. Invisible components that are activated
(triggered) when a character or other object
passes inside them

Colliders (but not rigidbodies) will notify their impacts but not crash

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Explain Screen Space, Viewport Space and World Space

A

Screen space: Bottom-left (0,0), top right (1,1). If using vector3, z-coordinate are world units in front of the camera (good for mouse positioning)

Viewport space: Normalised and relative to the camera (good for UI elements)

World space: Global coordinates

Example find mouse pos in world coord -> Camera.main.ScreenToWorldPoint(Input.mouseposition)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How could you rotate a gameobject a certain amount of degrees around WORLD y axis?

A

GameObject go:

go.Transform.Rotate(0f, xf, 0f, space.world)

If y-axis self it would be “space.self” instead

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Move a GameObject 6 units downwards in the world’s coordinate system

A

gameObject.transform.position += Vector3.down * 6;

17
Q

Move a GameObject 7 units directly towards another GameObject

A

Vector3 direction = (targetObject.transform.position - gameObject.transform.position).normalized;

gameObject.transform.position += direction * 7;

18
Q

Move a GameObject 10 units forward in whatever direction it is facing:

A

go.transform.position += go.transform.forward*10;

OR
(if maybe global coordinates)
gameObject.transform.Translate(Vector3.forward * 10, Space.Self);

19
Q

How can you find the distance between two GameObjects?

A

float distance = Vector3.Distance(obj.transform.position, pos);

OR

float distance = (go1.transform.position - go2.transform.position).magnitude

20
Q

Explain The Object Pool pattern – why it’s useful and how it operates

A

The Object Pool pattern is a design approach used to efficiently manage the creation and reuse of objects that are expensive to instantiate and destroy. Instead of repeatedly allocating and deallocating objects, a pool of pre-instantiated objects is maintained. These objects can be reused when needed and returned to the pool when not in use

-Performance: Reduces the overhead of frequent object instantiation and garbage collection, which is critical in performance-sensitive environments like games.
-Memory Efficiency: Limits the total number of objects in memory by reusing instances.
-Consistency: Ensures stable performance, especially in scenarios with frequent object creation, like spawning bullets or enemies

-Create a pool of objects at initialization.
-When needed, retrieve an object from the pool (activate it).
-Once no longer required, return the object to the pool (deactivate it).
-Grow the pool dynamically if all objects are in use.

21
Q

Under what circumstances does the OnCollisionEnter method get executed in a MonoBehaviour-derived script?

A

When Collider-To-Collider collides (interacts).

The Collider argument is simply a reference to the trigger component that interacted with ours

22
Q

How does Coroutines integrate with the game loop?

A

When a Coroutine is started, Unity schedules its execution alongside the Game Loop. The yield keyword pauses the Coroutine and lets the Game Loop continue its normal operations. Once the condition specified by the yield statement is met (e.g., waiting for a frame, a condition, or a time delay), the Coroutine resumes from where it left off.

23
Q

Write a Coroutine which carries out a sequence of actions over time:
- Gradually (frame by frame) moves its local game object at a speed of 1 metre
per second towards a Vector3 position.
- After the game object arrives at the position, waits 2 seconds.
- Then moves the game object in the same way to a second Vector3 position.

A

void Start() {
// Start the coroutine
StartCoroutine(MoveAndWaitCoroutine());
}

IEnumerator MoveAndWaitCoroutine() {
    // Move to the first position
    yield return StartCoroutine(MoveToPosition(position1));

    // Wait for 2 seconds
    yield return new WaitForSeconds(2f);

    // Move to the second position
    yield return StartCoroutine(MoveToPosition(position2));
}

IEnumerator MoveToPosition(Vector3 targetPosition) {
    // Continue moving until the GameObject is very close to the target
    while (Vector3.Distance(transform.position, targetPosition) > 0.01f) {
        // Move the GameObject closer to the target position at 1 meter/second
        transform.position = Vector3.MoveTowards(
            transform.position,
            targetPosition,
            1f * Time.deltaTime
        );

        // Wait for the next frame
        yield return null;
    }

    // Snap to the exact target position to avoid precision issues
    transform.position = targetPosition;
}
24
Q

Explain how Unity’s MonoBehaviour class provides tight integration with the Game Loop. Refer to appropriate methods of the MonoBehaviour class in your answer

A

Unity automatically calls these methods as part of its Game Loop, ensuring efficient execution of game logic at appropriate times. Developers don’t need to manually hook these methods into the loop, simplifying development and maintaining performance consistency

Start ()
Awake()
Update()
LateUpdate()
StartCoroutine()