[动画] Adding Physics and Getting Started With Coding

查看:1299 |回复:1 | 2021-4-8 11:54:59

您需要 登录 才可以下载或查看,没有账号?注册

x
At this point, you now have a world that is starting to look a little bit like a conventional computer game level.
In this chapter, we’re going to make it play like a conventional computer game level by adding some basic
physics and movement. For this, you’re going to be trying your hand at coding for the first time. Good luck!
So, we have tiled sprites that have a grassy pattern, and to mix things up a little, I’ve also created a
sprite to represent the ground underneath the grass, so that I can get a bit more creative with my level
design (see Figures 4-1 and 4-2).
Figure 4-1. The second ground tile
image.png
Figure 4-2. Some tiles just ready to be climbed on!
Chapter 4 ■ Adding Physics and Getting Started With Coding
60
I created the second dirt sprite the exact same way as the first one and then just copied it around
wherever I needed ground underneath the surface of my grass. You can do the same—just remember to hold
down Ctrl to keep the distances perfect using the snap to grid feature.
Now we’re going to do something even more exciting: create a game character and drop him into our
world. To begin with, we’re going to make the simplest character sprite we possibly can, which would be
another square. In the interest of making things a bit more interesting, we’ll also give him eyes.
Meet Squarey (Figure 4-3).
image.png
Squarey can be any size you like, but for simplicity I recommend keeping the same dimensions as you
used for the ground tiles.
Now add Squarey into your Sprites folder just as you did with the others. Make sure that you remember
to set the Pixels Per Unit to 50 again and then drag him into your scene. Name this new Game Object Player
and keep it separate from the Squares folder. It doesn’t matter where in the level you want to drag him, but I
chose to put him at the top of the hill I created (Figure 4-4).
Congratulations! You now have a main character. Problem is, he doesn’t actually do anything yet.
So, the next thing we want to do is to apply some physics so that gravity and other things will affect our
character. And you won’t believe how easy Unity makes this bit.
Figure 4-3. Squarey, mate, you don’t look so good
Figure 4-4. Squarey surveys his domain

Chapter 4 ■ Adding Physics and Getting Started With Coding
61
Using RigidBody 2D
As mentioned, the whole point of using a physics engine like Unity is so that we can access ready-made
scripts and elements to avoid coding everything ourselves from scratch. This makes it incredibly simple to
add something like gravity: all we have to do is drag a script onto our GameObject for it to take effect.
While your player is selected, click Add Component in the Inspector. Now click Physics 2D ➤ RigidBody 2D.
RigidBody 2D is the name of a script that works on 2D sprites and applies all the basic physics we could
want, such as gravity, friction, momentum, collision, and more.
The easiest way to see what this does, though, is to put it into action. So drag Squarey a little higher
in the Scene window and then click play. If everything goes according to plan, we now have a sad-looking
Squarey who simply falls from the top of the screen and off the bottom. Squarey, meet gravity!
Using Colliders
The astute will note that there’s something missing here. Of course, we don’t actually want Squarey to fall
through the ground underneath him; we want him to land on it. Fortunately, this is an easy fix too.
Just click Squarey again and then Add Component ➤ Physics 2D ➤ Box Collider. You should now be
able to see both RigidBody 2D and Box Collider 2D in the Inspector.
What’s more, you should also notice a thin green outline around Squarey. This is the collider, which
essentially defines the boundaries of your sprite and tells RigidBody 2D where the physical mass that makes
up the character starts and stops.
Click play and you’ll see that the character still falls through the ground below. Hopefully, you’ve
guessed already that this is because our tiles also need to have colliders attached. To do this, drag a square
around the tiles in your Scene view using the mouse in order to select them all at once. You can do this
just the same way you would select a bunch of icons on your desktop (Figure 4-6), or by clicking the first
item in the hierarchy and then the last item while holding down Shift. You can also use Ctrl for making
bulk selections, just as you would in most Windows programs. This is a trick that will often come in handy,
although there’s another method for making mass changes that we will look at shortly. Make sure to deselect
the camera and then add a collider in the Inspector. This will now be applied to every GameObject selected
all at once.
Figure 4-5. The green outline shows Squarey’s collider

Chapter 4 ■ Adding Physics and Getting Started With Coding
62
Notice that we’re not adding the RigidBody 2D to our ground tiles. That’s because we don’t want them
to fall off the screen.
Now click play, and if everything goes according to plan our character will fall and land on the ground
(Figure 4-7).
If you want to test just how detailed RigidBody 2D is, position Squarey so that he’s partly hanging over
the edge of one of the steps and then click play again. When he lands, he should tip and actually roll down
the stairs.
At this point, we now already have a game that acts the way we expect it to. The next step should
probably be to make it interactive. Get ready: this is where the actual coding comes in.
Figure 4-6. Later we will discuss using prefabs to avoid having to select multiple GameObjects

Figure 4-7. Success!

Chapter 4 ■ Adding Physics and Getting Started With Coding
63
Getting Started with Coding in C#
Before you begin coding, we first need to make a folder to contain all of our scripts within the Assets
directory. Right-click in the Project view and select Create ➤ Folder, just as you did when you created the
Sprites and Scenes folders. Call this new folder Scripts and then open it up.
In here, you’re again going to right-click and this time select Create ➤ C# Script. Call this Player and
then double-click it to open it. You’ll now be opening Visual Studio for the first time. But first, you need to
sign in. To do that, you can just use your Microsoft account (the one you probably use to log into Windows
and Hotmail). If you don’t have one, you’ll be given the opportunity to create one.
Once you’re in, the UI should look something like Figure 4-8.
For now, we’re concentrating on that big window in the middle, which is where we can input and edit
code. We’re choosing to code in C# here because it’s somewhat similar to Java—the language used in most
Android development—only slightly simpler. One thing to keep in mind when coding in C# is that every line
needs to end with a semicolon or an open or closed curly bracket. If you miss this, you’ll get an error. You’ll
probably find that it’s surprisingly easy to miss this crucial detail and then spend ages routing through your
code trying to find out why it won’t run.
What you might also notice here is that the document actually isn’t empty but instead has several lines
of code already within it. These are functions, which are standalone collections of code that are called at
specific times. The two functions we have here will be present in every script we create and help to provide a
little bit of structure for what we’re about to do.
The whole thing should look like the following:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
// Use this for initialization
void Start () {
}
Figure 4-8. Welcome to Visual Studio

Chapter 4 ■ Adding Physics and Getting Started With Coding
64
// Update is called once per frame
void Update () {
}
}
Don’t worry about the top two lines just yet. The third line that reads public class is really just naming
the script we’ve created, and the following two sections (void Start and void Update) are our functions.
Two other things to note are the forward slashes. Whenever a line starts with two forward slashes in C#,
that means it’s a comment and that it won’t have any effect on the way the code runs. In other words,
this is how you can write yourself messages in case you forget what a line of code does. When teams of
programmers work together, commenting like this is immensely important to ensure that every member
knows what everything does.
The two comments that are already here describe what the functions do. The first one says "Use this
for initialization", so void Start will run whenever the script is first introduced into the scene. The
second comment says "Update is called once per frame", so void Update runs repeatedly at a very fast
speed as the game refreshes.
To demonstrate this, let’s try and make our character move right across the screen. To do that, we first
need to refer to some important elements that we’re going to be working with in the code. In this case, we
need to work with the RigidBody 2D script that is attached to our Player GameObject. And to do that, we
need to add the following code:
public class Controls : MonoBehaviour {
public Rigidbody2D rb;
void Start () {
rb = GetComponent<Rigidbody2D>();
}
What’s happening here is that we’re creating a reference to a RigidBody 2D and calling it rb
(short for RigidBody). Then, when the script initializes, we’re telling it that the instance of RigidBody 2D
to work with is the GameObject that our script is attached to (in a moment, we’ll be attaching this to the
Player GameObject).
Don’t worry if this is all a little confusing: you can just copy and paste the code for now and it will make
more sense later on.
Finally, we’re going to add the following line of code to our Update function:
void Update () {
rb.velocity = new Vector2(1, rb.velocity.y);
}
This is simply adding a veleocity with the value 1 to the horizontal X coordinate of the RigidBody
(Vector is a coordinate). Because this is in Update, that means that it should run each time the scene
refreshes—which happens incredibly quickly. The whole thing should look like the following:
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour {
public Rigidbody2D rb;
Chapter 4 ■ Adding Physics and Getting Started With Coding
65
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
rb.velocity = new Vector2(1, rb.velocity.y);
}
}
Make sure you remember to save your work!
Now all that is left to do is to head back to Unity and add the Player script to the Player character.
We do this just the same as we added RigidBody 2D: select the Player GameObject, click Add Component,
and then Scripts &#10148; Player. Now click play and you should find that Squarey moves continually to the right
and then falls down the steps to his ultimate doom (Figure 4-9).

Only once you’ve attached the script to your GameObject will it have any effect, and you could just as
easily have added this to a ground tile for the same effect.

2021-4-8 11:54:59  
 赞 赞 0

使用道具 登录

1个回答,把该问题分享到群,邀请大神一起回答。
2#
这个不错 感谢分享
回复 收起回复
2024-12-4 14:22:38   回复
 赞 赞 0

使用道具 登录

CG 游戏行业专业问题

图文教程技术文章技术文库动画
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表