Как изменить позицию объекта в unity через скрипт
Перейти к содержимому

Как изменить позицию объекта в unity через скрипт

  • автор:

Transform.position

Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.

Submission failed

For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.

Description

The world space position of the Transform.

The position property of a GameObject’s Transform, which is accessible in the Unity Editor and through scripts. Alter this value to move a GameObject. Get this value to locate the GameObject in 3D world space.

The example gets the Input from Horizontal and Vertical axes, and moves the GameObject up/down or left/right by changing its position.

Unity Fundamentals — Moving a game object

Understand transform position and learn simple methods on how to move game objects in Unity.

Resources

Basics first

Each object in Unity holds Transform. Transform is responsible for position, rotation, and scale manipulation of the object.

Each object placed in the Unity scene has some initial position, rotation, and transform.

The object is residing either in 3D or 2D space, depending on the type of the project. In our case, we will be working on a 3D project.

Let’s take a look at the example of a Capsule object located in 3D space.

The Center of the plane is located at the position (0,0,0) whereas the point in 3d space is determined by 3 values laying on the (X, Y, Z) axis.

Each position on the axis holds a different value. Starting from the center position (0,0,0) going to the right is increasing X value, going upwards Y value is increasing and lastly going forward Z value is increasing. Going in the opposite direction of the mentioned axis causing a decrease of the value.

In order to find a point in 3D space you need to know all 3 coordinates, (X, Y, Z)

Now let’s see where Capsule would be located at the position (1,1,1)

The Capsule is now located exactly 1 Unity meter on X-axis, 1 meter on the Z-axis, and 1 meter up on Y-axis. Maybe, you are asking the question “Why is the capsule 1 meter on Y?”

Well, the Capsule object has 2 meters, so the center of the capsule is 1 meter above the ground.

That’s why it needs to be placed 1 meter on the Y-axis. Otherwise, it would be half-way body in the middle of the plane.

Change position in the code

You can change the object position in the code by manipulating the transform property of the object.

The position is represented internally by the struct called Vector3. Vector3 holds 3 values -> x,y,z

Let’s move the game object to the position (1,1,1)

That’s are the basics you need to know about the position. Remember position is a location in the space represented by the (X, Y, Z) value, each laying on its own axis.

Now we are going to create a functionality to move the Capsule when a player is pressing input keys on the keyboard.

Movement script

First, create a new script called Movement.cs and add it to the Capsule object.

We will place movement functionality into the Update method. Update is executed during the entire play-time of the game — how often depends on the frame-rate of your game.

About Update

The Update method is called once per frame.

If the game is running at 140fps then Update is called 140 times per second. This is making it a great spot for functionality that should happen constantly during the game duration.

Handling player input is usually a functionality that is placed in the Update method.

Capture a player input

In order to move a game object, we need to capture a player input. If a player is using as the input device a keyboard, we want to capture as he is pressing arrow keys or AWSD keys on the keyboard.

For this purpose, we can write the following code in Update.

Input values are usually values in the range between -1 and 1. Try it out.

Horizontal Axis

Horizontal value of 0 means that NO “movement” key is pressed.

Value 1 means that the player is pressing the “right” arrow or “D” key (player wants to move right)

Value -1 means that the player is pressing the “left” arrow or “A” key (player wants to move left)

Vertical Axis

Vertical value of 0 means that NO “movement” key is pressed.

Value 1 means that the player is pressing the “up” arrow or “W” key (player wants to move forward)

Value -1 means that the player is pressing the “down” arrow or “S” key (player wants to move backward)

To get from 0 to 1 or 0 to -1 value while the user is holding down movement keys, will not happen immediately, but with default settings of Unity, it will happen super-fast!

So while holding “right” arrow for one second you can get values in horizontal input, 0, 0.1, 0.3, 0.5, 0.7, 1, 1, 1, 1….reaching 1 value almost imidiately.

These are just illustrational values, you can get completely different ones.

Since we can capture the player input we are almost ready to move.

Ready to move

Let’s extend the current implementation.

You will notice one thing. We are moving too fast.

First, let’s explain the code above.

We are storing the vertical and horizontal values in the Vector3 structure, in order to apply them to change the game object position.

As I mentioned before, every game object has a position represented by (X, Y, Z) value.

We need to apply this change of position in form of Vector3 and then provide it to the Translate method. The Translate method will move a game object in direction and distance of translation.

Imagine these 3 cases:

The object will move right when a player is holding the “right” arrow or “D” because Vector3 is holding value (1,0,0), which expresses a change in direction on X-axis.

The object will move forward when a player is holding the “up” arrow or “W” because Vector3 is holding a value (0,0,1), which expresses a change in direction on Z-axis.

The object will move diagonally when a player is holding the “up” arrow or “W” at the same time as the “right” arrow or “D” key, because Vector3 is holding value (1,0,1), which expresses a change in direction on X and Z axis.

These changes are applied to the game object’s current position. You can think of the game object as the center of the plane.

Why is the object moving fast?

The game object is moving fast because Update is called many times per one second. Imagine stable frame-rate(FPS) to be 50. 50 FPS means that your game is updated 50 times per second therefore Update is called 50 times per second.

This also means that holding input keys for the length of 1 second would result in 50 executions of

so if Vector3 would be (1,0,0) then I would move each second 50 meters to the right because Update is called 50 times per second.

Our functionality is frame-dependent. In order to move only 1 meter per second, we need to decrease the value of the movement.

Time delta

First, update translate like this

If you will play the game now you will notice that movement is fixed and you are moving nice and slowly.

Time delta is the completion time of the last frame in seconds.

Again, imagine stable frame-rate 50 frames per 1 second. Completion time of each frame would be 0.02 second because 50 * 0.02 = 1 second

If you multiple the movement by 0.02 you will lower its value, if this happens 50 times per second then Vector3(0,0,1) will apply movement of 1 meter per second.

Now the functionality of the movement is time-dependent. You will use Time.deltaTime a lot.

Final improvements

If the movement is too slow then multiple the movement with some higher value. Let’s say you want to move the Capsule to move 6 meters per second.

Now the final code.

You can notice I called Normalize method on movement. In the case of diagonal movement, you will move faster. Normalize will “fix” it and movement will be the same in every direction.

I am explaining Normalize in much more detail in my other Youtube video: https://www.youtube.com/watch?v=oCU8Ew1XTbs&t=3s

Recap

Now you should have a basic understanding of how to move a game object in Unity. Everything is just about the change of the position over some time-interval.

Web server is returning an unknown error Error code 520

There is an unknown connection issue between Cloudflare and the origin web server. As a result, the web page can not be displayed.

What can I do?

If you are a visitor of this website:

Please try again in a few minutes.

If you are the owner of this website:

There is an issue between Cloudflare’s cache and your origin web server. Cloudflare monitors for these errors and automatically investigates the cause. To help support the investigation, you can pull the corresponding error log from your web server and submit it our support team. Please include the Ray ID (which is at the bottom of this error page). Additional troubleshooting resources.

Cloudflare Ray ID: 7a6db093e4592d4f • Your IP: Click to reveal 88.135.219.175 • Performance & security by Cloudflare

Unity Transform explained in simple terms

When you add a Gameobject in the Unity scene the first thing that you notice in the inspector window is the Transform component. Unity transform defines the position, rotation, and size of a Gameobject in the game world. Transform is the most basic component in Unity but it’s also the most important. You cannot define a Gameobject in Unity without Transform. Even an empty Gameobject has the Transform component. In this post, we will see what the Unity transform component does and how you can use it in your game.

What is Transform in Unity?

Unity Transform is a class like any other component in Unity. This class contains three important properties. These are position, rotation, and scale.

Position defines the X, Y, and Z coordinates of the Gameobject. Rotation is the degree of rotation of the Gameobject in the X, Y, and Z-axis. The scale is the size of the Gameobject in these coordinates. One important thing to take note of here is all these values are relative to the Gameobject’s parent object. Say, the transform position of the Gameobject is 0,0,5 and it’s a child of another object which is at the position 0,0,5 then the overall position of the child is 0,0,10 from the origin.

Unity Transform Ven diagram

Unity Transform major properties

Unity Transform position

Position as the name suggests is used to change the position of the object in the scene. But it cannot be used to move players with physics as when you change the transform position the object is teleported from the initial position to the target position.

You can use it in the following cases

  1. Find the location of any Gameobject in the scene.
  2. To spawn a Gameobject to a particular location.
  3. Move an object without satisfying physics laws.
  4. To make the camera follow the player.
  5. Define target location of moving objects.
Example script

in Unity Transform position requires a Vector3 for a 3D object and a Vector2 for a 2D object.

Above code moves the object to 0,10,0 when the object is initialized.

Unity Transform Rotation

Rotation specifies the orientation of the Gameobject in the scene. Depending upon the axis of rotation the value of the X, Y, and Z coordinates will vary. Rotation is described in Euler angles in Unity and quaternion is used to store the data. Don’t get afraid of the name Quaternion, it’s just a variable type to store the rotation data. If you want to get into the mathematics part of quaternion you can read this article from mathworld.

Rotation can be used for many things in a game. Some examples are below

  1. Rotate the camera in the game to change the view.
  2. You can spin an object continuously using rotation.
  3. Rotate light to get day and night cycle.
  4. Get the object orientation.
  5. Tilt an object.
Sample Rotation script

Even though a quaternion is needed to save the rotation data you can save individual axis data in float variable.

This script takes the rotation of the object into a variable rot and then saves the individual axis data in xrot, yrot and zrot when the script is initialized. It then rotates the object by 5 degrees every frame along the x axis.

Unity Transform Scale

Transform scale is the least used transform. Mostly the object transform is set at the beginning in the inspector window and then left untouched. The reason why the scale is not disturbed during gameplay is it can make the object look absurd and might interfere with other gameobjects. So, unless you are very sure of the outcome of changing the scale it’s better to set it beforehand.

Understanding Local Transform

In Unity or 3D space in general, there are two spaces used for reference. One is global space and the other is local space. Let’s see an example to understand it better. Say there is a ball in the coordinate 10,0,0 and you want to move it to 0,0,0 in world space. But the ball has a parent to it which is in the coordinate -20,0,0. Now to move the ball to 0,0,0 you must know the object’s location with respect to world space.

The coordinates of the child are always with respect to the parent. So, the actual position of the child ball object in world space is -10,0,0 but in local space, it is 10,0,0. So to move the object to 0,0,0 in the world space you need to add 10,0,0 to the position of the child.

In Unity, this difference is obtained using the local keyword. If you want to move the object relative to the parent then you should use transform.localPosition rather than transform.postion. Local space can be confusing in the beginning but you will understand it as you apply it in your game.

There are many other features of Unity Transform but this summarizes the basics you need to understand to make simple games. If you have any queries leave them in the comment below.

Unity transform other important properties

Transform.Up

Returns the axis representing the top of the gameobject. In other words, the red axis in the gizmo.

Transform.Right

Returns the axis representing the right side of the gameobject. Unlike Vector3 in Unity, transform considers the rotation of the game object.

Transform.forward

Returns the direction in which the game object is facing. You can use this to move the object in the direction it’s facing.

Transform.parent

Returns the parent of the game object.

Transform.eulerAngles

Returns the rotation of the game object in Euler angle degrees.

Transform.childCount

Returns the number of children the gameobject has in the hierarchy.

Important public methods of Unity transform

Transform.Find

This method is very similar to Gameobject.find but can only be used to find the child of this gameobject. You can find the gameobject’s child using its name in this method. You can also find the child using Transform.GetChild but it takes the index as input.

Transform.Lookat

This is used to set the forward direction of the gameobejct. Can be very useful to make your gameobject point towards the required direction.

Transform.Rotate

Tranform rotation which we came across in the beginning takes a quaternion as input. In order to set the rotation by a few Euler angles you can use Transform.Rotate. You can also use Transform.RotateAround to rotate an object around a axis.

Transform.Translate

It’s used to move an object in Unity in the direction of a vector at a speed equal to the magnitude of the vector.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *