Reader small image

You're reading from  Unity Cookbook - Fifth Edition

Product typeBook
Published inNov 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781805123026
Edition5th Edition
Languages
Tools
Right arrow
Authors (3):
Shaun Ferns
Shaun Ferns
author image
Shaun Ferns

Shaun is a lecturer at Technological University Dublin. He is currently teaching on the BA (Hons) in Creative Digital Media where he is lead in the delivery of the Multimedia Stream. He is currently exploring serious games for construction-related training as well as the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts. His educational research is currently driven by his interest in self-determined learning (heutagogy), rhizomatic learning theory, micro-credentialing /digital badging, and curriculum development.
Read more about Shaun Ferns

Sinéad Murphy
Sinéad Murphy
author image
Sinéad Murphy

Sinead Murphy is currently Data Analytics Manager for the Irish NGO Trocaire. She has over 25 years of computing experience, including freelance IT training and database consulting, university lecturing in mathematics, IT skills and programming at TU Dublin (Ireland) and Middlesex University (London). She is a published academic, with undergraduate and postgraduate degrees in mathematics, computing and data science. She is passionate about the use of IT for understanding and visualising data, and using that understanding to make meaningful differences in the world. She is currently exploring the use of Python and Unity for data analytics and interactive visualisations.
Read more about Sinéad Murphy

View More author details
Right arrow

Controlling and Choosing Positions

In this chapter, we will introduce a few recipes and demonstrate a selection of approaches to character control, spawn points, and checkpoints. In the next chapter, we’ll look at waypoints for AI-controlled characters traversing Unity navigation meshes.

Many GameObjects in games move! Movement can be controlled by the player, by the (simulated) laws of physics in the environment, or by Non-Player Character (NPC) logic. For example, objects follow the path of a waypoint, or seek (move toward) or flee (away) from the current position of a character. Unity provides several controllers for first- and third-person characters, and vehicles such as cars and airplanes. GameObject movement can also be controlled through the state machines of the Unity Mecanim animation system.

However, there may be times when you wish to tweak the player character controllers from Unity or write your own. You might wish to write directional logic – simple...

Using a rectangle to constrain 2D Player object movement

Basic character movement in 2D (within a bounding rectangle) is a core skill for many 2D games, so this first recipe will illustrate how to achieve these features for a 2D game. The remaining recipes will then build on this approach for 3D games.

Since in Chapter 3, Inventory and Advanced UIs, we created a basic 2D game template, we’ll adapt this game to restrict the movement to a bounding rectangle:

Figure 11.1: Movement of a character within the rectangular area

Getting ready

This recipe builds on the simple 2D mini game called Simple2DGame_SpaceGirl from the first recipe of Chapter 3, Inventory and Advanced UIs. Start with a copy of this game, or use the provided completed recipe project as the basis for this recipe.

How to do it...

To create a 2D sprite controlled by the user with movement that is limited to within a rectangle, follow these steps:

  1. Create a new, empty GameObject...

Player control of a 3D GameObject (and limiting movement within a rectangle)

Many of the 3D recipes in this chapter are built on this basic project, which constructs a scene with a textured terrain, a Main Camera, and a red cube that can be moved around by the user with the four directional arrow keys:

Figure 11.5: Basic 3D scene with a player-controlled cube

The bounds of movement of the cube will be constrained using the same technique that we used in the previous 2D recipe.

Getting ready

For this recipe, we have prepared the image you need in a folder named Assets, in the 10_02 folder.

How to do it...

To create a basic 3D cube-controlled game, follow these steps:

  1. Create a new, empty Unity 3D project.
  2. Import the single Terrain Texture named SandAlbedo from the 10_02 provided folder, in the Assets folder.
  3. Create a new terrain by going to GameObject | 3D Object | Terrain.
  4. With this new Terrain GameObject selected in the Hierarchy...

Choosing destinations – finding a random spawn point

Many games make use of spawn points and waypoints. This recipe will show you how to choose a random spawn point, and then the instantiation of an object at that chosen point:

Figure 11.8: Sphere randomly spawned at one of the spawn point capsules

As shown in the preceding figure, the sphere has been spawned at one of the four capsule spawn points.

Getting ready

This recipe builds upon the previous recipe. So make a copy of this project, open it, and then follow the steps in the next section.

How to do it...

To find a random spawn point, follow these steps:

  1. In the Scene panel, create a sphere (by navigating to GameObject | 3D Object | Sphere) scaled to as (2, 2, 2) at position (2, 2, 2) and apply the m_red material.
  2. In the Project panel, create a new prefab based on your sphere by dragging the Sphere GameObject from the Hierarchy panel into the Project panel. Rename this new prefab...

Choosing destinations – finding the nearest spawn point

Rather than just choosing a random spawn point or waypoint, sometimes, we want to select the one that’s closest to an object (such as the player’s GameObject). In this recipe, we will modify the previous recipe to find the nearest spawn point to the player’s cube, and then use that location to spawn a new red ball prefab:

Figure 11.10: Spawning a sphere at the spawn point capsule that is nearest the player cube

Getting ready

This recipe builds upon the previous recipe. So make a copy of that project, open it, and then follow the steps in the next section.

How to do it...

To find the nearest spawn point, follow these steps:

  1. Add the following method to the C# script class called SpawnPointManager:
        public GameObject GetNearestSpawnpoint (Vector3 source){
           GameObject nearestSpawnPoint = spawnPoints[0];
           Vector3 spawnPointPos = spawnPoints[0].transform...

Choosing destinations – respawning to the most recently passed checkpoint

A checkpoint usually represents a certain distance throughout the game (or perhaps a race track) in which an agent (user or NPC) has succeeded in reaching. Reaching (or passing) checkpoints often results in bonus awards, such as extra time, points, ammo, and so on. Also, if a player has multiple lives, then a player will often only be respawned back as far as the most recently passed checkpoint, rather than right to the beginning of the level.

This recipe will demonstrate a simple approach to checkpoints, whereby once the player’s character has passed a checkpoint if they die, they are moved back to the most recently passed checkpoint:

Figure 11.11: The three kill spheres, separated by two checkpoints

In the preceding screenshot, we can see a player-controlled cube on the right. The game area contains three spheres that will kill the player when hit. The game area is divided into...

Moving objects by clicking on them

Sometimes, we want to allow the user to interact with objects through mouse pointer clicks. In this recipe, we will allow the user to move an object in a random direction by clicking on it.

Getting ready

This recipe builds upon the player-controlled 3D cube Unity project that you created at the beginning of this chapter: Player control of a 3D GameObject. So make a copy of that project, open it, and then follow the steps for this recipe.

The result of this recipe should look as follows:

Figure 11.12: A pyramid of cubes falling down after being clicked on

How to do it...

To move objects by clicking on them, follow these steps:

  1. Delete the Cube-player GameObject.
  2. Set the position of Main Camera to (0, 3, -5) and its rotation to (25, 0, 0).
  3. Create a C# script class called ClickMove:
    using UnityEngine;
    [RequireComponent(typeof(Rigidbody))]
    public class ClickMove : MonoBehaviour {
     public float...

Firing projectiles in the direction of movement

Another common use of force is to apply it to a newly instantiated object, making it a projectile traveling in the direction that the player’s GameObject faces. That’s what we’ll create in this recipe. The result of this recipe should look as follows:

Figure 11.13: Projectiles being fired by the player’s object

In the preceding screenshot, on the left, we can see a player-controlled tank, while on the right, we can see three sphere projectiles that have been fired from the player’s character.

Getting ready

This recipe builds upon the player-controlled 3D cube Unity project that you created at the beginning of this chapter. So make a copy of that project, open it, and then follow the steps for this recipe.

How to do it...

To fire projectiles in the direction of movement, follow these steps:

  1. Create a new Sphere GameObject (by navigating to Create | 3D Object | Sphere...

Further reading

The following are some useful resources to learn more about controlling Unity object positions and movements:

Throughout this chapter, we have kept to a good rule of thumb:

Always listen for input in Update().

Always apply physics in FixedUpdate().”

You can learn more about why we should not check for input in FixedUpdate() in the Unity Answers thread (which is also the source for the preceding quote from user Tanoshimi) at https://answers.unity.com/questions/1279847/getaxis-being-missed-in-fixedupdate-work-around.html.

Learn more on Discord

To join the Discord community for this book – where you can share feedback, ask questions to the author, and learn about new releases – follow the QR code below:

https://packt.link/unitydev

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Unity Cookbook - Fifth Edition
Published in: Nov 2023Publisher: PacktISBN-13: 9781805123026
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Authors (3)

author image
Shaun Ferns

Shaun is a lecturer at Technological University Dublin. He is currently teaching on the BA (Hons) in Creative Digital Media where he is lead in the delivery of the Multimedia Stream. He is currently exploring serious games for construction-related training as well as the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts. His educational research is currently driven by his interest in self-determined learning (heutagogy), rhizomatic learning theory, micro-credentialing /digital badging, and curriculum development.
Read more about Shaun Ferns

author image
Sinéad Murphy

Sinead Murphy is currently Data Analytics Manager for the Irish NGO Trocaire. She has over 25 years of computing experience, including freelance IT training and database consulting, university lecturing in mathematics, IT skills and programming at TU Dublin (Ireland) and Middlesex University (London). She is a published academic, with undergraduate and postgraduate degrees in mathematics, computing and data science. She is passionate about the use of IT for understanding and visualising data, and using that understanding to make meaningful differences in the world. She is currently exploring the use of Python and Unity for data analytics and interactive visualisations.
Read more about Sinéad Murphy