Как изменить transform position unity

Suggest a change

Suggest a change

Success!

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.

Close

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.

Close

Your name

Your email

Suggestion*

Cancel

Switch to Manual

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.

using UnityEngine;

public class ExampleClass : MonoBehaviour { //movement speed in units per second private float movementSpeed = 5f;

void Update() { //get the Input from Horizontal axis float horizontalInput = Input.GetAxis("Horizontal"); //get the Input from Vertical axis float verticalInput = Input.GetAxis("Vertical");

//update the position transform.position = transform.position + new Vector3(horizontalInput * movementSpeed * Time.deltaTime, verticalInput * movementSpeed * Time.deltaTime, 0);

//output to log the position change Debug.Log(transform.position); } }

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

Suggest a change

Success!

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.

Close

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.

Close

Your name

Your email

Suggestion*

Cancel

Switch to Manual

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.

using UnityEngine;

public class ExampleClass : MonoBehaviour { //movement speed in units per second private float movementSpeed = 5f;

void Update() { //get the Input from Horizontal axis float horizontalInput = Input.GetAxis("Horizontal"); //get the Input from Vertical axis float verticalInput = Input.GetAxis("Vertical");

//update the position transform.position = transform.position + new Vector3(horizontalInput * movementSpeed * Time.deltaTime, verticalInput * movementSpeed * Time.deltaTime, 0);

//output to log the position change Debug.Log(transform.position); } }

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

class in
UnityEngine

/

Inherits from:Component

/

Implemented in:UnityEngine.CoreModule

Suggest a change

Success!

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.

Close

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.

Close

Your name

Your email

Suggestion*

Cancel

Switch to Manual

Description

Position, rotation and scale of an object.

Every object in a Scene has a Transform.
It’s used to store and manipulate the position, rotation and scale of the object.
Every Transform can have a parent, which allows you to apply position, rotation and scale hierarchically. This is the hierarchy seen in the Hierarchy pane.
They also support enumerators so you can loop through children using:

using UnityEngine;

public class Example : MonoBehaviour { // Moves all transform children 10 units upwards! void Start() { foreach (Transform child in transform) { child.position += Vector3.up * 10.0f; } } }

Properties

childCount The number of children the parent Transform has.
eulerAngles The rotation as Euler angles in degrees.
forward Returns a normalized vector representing the blue axis of the transform in world space.
hasChanged Has the transform changed since the last time the flag was set to ‘false’?
hierarchyCapacity The transform capacity of the transform’s hierarchy data structure.
hierarchyCount The number of transforms in the transform’s hierarchy data structure.
localEulerAngles The rotation as Euler angles in degrees relative to the parent transform’s rotation.
localPosition Position of the transform relative to the parent transform.
localRotation The rotation of the transform relative to the transform rotation of the parent.
localScale The scale of the transform relative to the GameObjects parent.
localToWorldMatrix Matrix that transforms a point from local space into world space (Read Only).
lossyScale The global scale of the object (Read Only).
parent The parent of the transform.
position The world space position of the Transform.
right The red axis of the transform in world space.
root Returns the topmost transform in the hierarchy.
rotation A Quaternion that stores the rotation of the Transform in world space.
up The green axis of the transform in world space.
worldToLocalMatrix Matrix that transforms a point from world space into local space (Read Only).

Public Methods

DetachChildren Unparents all children.
Find Finds a child by name n and returns it.
GetChild Returns a transform child by index.
GetLocalPositionAndRotation Gets the position and rotation of the Transform component in local space (that is, relative to its parent transform).
GetPositionAndRotation Gets the position and rotation of the Transform component in world space.
GetSiblingIndex Gets the sibling index.
InverseTransformDirection Transforms a direction from world space to local space. The opposite of Transform.TransformDirection.
InverseTransformPoint Transforms position from world space to local space.
InverseTransformVector Transforms a vector from world space to local space. The opposite of Transform.TransformVector.
IsChildOf Is this transform a child of parent?
LookAt Rotates the transform so the forward vector points at /target/’s current position.
Rotate Use Transform.Rotate to rotate GameObjects in a variety of ways. The rotation is often provided as an Euler angle and not a Quaternion.
RotateAround Rotates the transform about axis passing through point in world coordinates by angle degrees.
SetAsFirstSibling Move the transform to the start of the local transform list.
SetAsLastSibling Move the transform to the end of the local transform list.
SetLocalPositionAndRotation Sets the position and rotation of the Transform component in local space (i.e. relative to its parent transform).
SetParent Set the parent of the transform.
SetPositionAndRotation Sets the world space position and rotation of the Transform component.
SetSiblingIndex Sets the sibling index.
TransformDirection Transforms direction from local space to world space.
TransformPoint Transforms position from local space to world space.
TransformVector Transforms vector from local space to world space.
Translate Moves the transform in the direction and distance of translation.

Inherited Members

Properties

gameObject The game object this component is attached to. A component is always attached to a game object.
tag The tag of this game object.
transform The Transform attached to this GameObject.
hideFlags Should the object be hidden, saved with the Scene or modifiable by the user?
name The name of the object.

Public Methods

BroadcastMessage Calls the method named methodName on every MonoBehaviour in this game object or any of its children.
CompareTag Checks the GameObject’s tag against the defined tag.
GetComponent Returns the component of type if the GameObject has one attached.
GetComponentInChildren Returns the Component of type in the GameObject or any of its children using depth first search.
GetComponentInParent Returns the Component of type in the GameObject or any of its parents.
GetComponents Returns all components of Type type in the GameObject.
GetComponentsInChildren Returns all components of Type type in the GameObject or any of its children using depth first search. Works recursively.
GetComponentsInParent Returns all components of Type type in the GameObject or any of its parents.
SendMessage Calls the method named methodName on every MonoBehaviour in this game object.
SendMessageUpwards Calls the method named methodName on every MonoBehaviour in this game object and on every ancestor of the behaviour.
TryGetComponent Gets the component of the specified type, if it exists.
GetInstanceID Gets the instance ID of the object.
ToString Returns the name of the object.

Operators

bool Does the object exist?
operator != Compares if two objects refer to a different object.
operator == Compares two object references to see if they refer to the same object.

Movement is one of the most common things you will need to know more about when it comes to frameworks and engines.
This is the reason I’ve decided to do a small write up of the most common ways on how to move a object.

The most common way of moving objects in Unity is to set transform.position to a Vector2 or a Vector3. This will change the position of the GameObject that holds the component from which the code is called from. But it is also possible to call transform.Translate(vector), which will add the vector the current position. In order to move a object towards another position you can use a several methods that are callable on the Vector3 or Vector2 structs. Such as Vector3.MoveTowards(a,b,distance) or Vector3.Lerp(a,b,t). A example of moving a object to a point would be “transform.position = Vector3.MoveTowards(transform.position, point, Time.Deltatime * speed);”. People also often use libraries to move objects, an example of a good tweening library would be DOTween.

setting transform.position

The quickest way to move a object to a specific position is to set the transform.position field.
This will change the position of the game object that the component is attached to.

Another way of moving the object, opposed to setting it’s position is to call transform.Translate(direction).

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

Show hidden characters

using UnityEngine;
public class MoveObject : MonoBehaviour
{
void Start()
{
// Changes the position to x:1, y:1, z:0
transform.position = new Vector3(1, 1, 0);
// It is also possible to set the position with a Vector2
// This automatically sets the Z axis to 0
transform.position = new Vector2(1, 1);
// Moving object on a single axis
Vector3 newPosition = transform.position; // We store the current position
newPosition.y = 100; // We set a axis, in this case the y axis
transform.position = newPosition; // We pass it back
}
private void Update()
{
// We add +1 to the x axis every frame.
// Time.deltaTime is the time it took to complete the last frame
// The result of this is that the object moves one unit on the x axis every second
transform.position += new Vector3(1 * Time.deltaTime, 0, 0);
}
}

EASY WAY TO SET SINGLE AXIS USING EXTENTION METHODS

In case you want to move a object on a single axis, and don’t want to create a local variable each time you do it. You can use extention methods. Extention methods give extended functionality to existing classes and structs. These are useful particually since some classes are not modifyable within Unity. Such as the Vector3 struct.

When you import the script below, you are able to set the X position of a object to 20 by calling:
transform.SetX(20);

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

Show hidden characters

using UnityEngine;
public static class TransformExtentions
{
public static void SetX(this Transform transform, float x)
{
transform.position = new Vector3(x, transform.position.y, transform.position.z);
}
public static void SetY(this Transform transform, float y)
{
transform.position = new Vector3(transform.position.x, y, transform.position.z);
}
public static void SetZ(this Transform transform, float z)
{
transform.position = new Vector3(transform.position.x, transform.position.y, z);
}
}

using Vector3.Movetowards

Sometimes you want an object to move to a specific destination. Vector3.Movetowards is the simplest way of achieving this.
You specify your initial point from which you want to move. And the point which you want to move toward, along with a variable that specifys at what speed it should move.

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

Show hidden characters

using UnityEngine;
public class MoveTowardsExample : MonoBehaviour
{
[SerializeField] private Vector3 target = new Vector3(1, 1, 1);
[SerializeField] private float speed = 1;
private void Update()
{
// Moves the object to target position
transform.position = Vector3.MoveTowards(transform.position, target, Time.deltaTime * speed);
}
}

Linear interpolation with Vector3.LERP

How linear interpolation works is that it interpolates between two points. A, B based on a input value (T).
So for example A:0, B:10, and T: 0.5 would return the value of 5.

This is often used in a wrong way by developers, this is because they call Vector3.Lerp(posA,posB, Time.Deltatime).
Which results in a object that eases towards the target, without ever fully reaching it.
Calling it in that way would be the same as calling transform.position += distance* 0.1f; .
Constantly adding a portion of the remaining distance, which will eventually be 0.052131 and then 0.025… etc.

The example given below is the correct way to make a object move from point A to B.
As a addition to this I’ve also included the code on how this function is made. 

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

Show hidden characters

using UnityEngine;
public class LerpExample : MonoBehaviour
{
[SerializeField] private Vector3 pointA = new Vector3(2, 0, 0);
[SerializeField] private Vector3 pointB = new Vector3(2, 0, 0);
[SerializeField] private float speed = 1;
private float t;
private void Update()
{
t += Time.deltaTime * speed;
// Moves the object to target position
transform.position = Vector3.Lerp(pointA, pointB, t);
// Flip the points once it has reached the target
if (t >= 1)
{
var b = pointB;
var a = pointA;
pointA = b;
pointB = a;
t = 0;
}
}
// What Linear interpolation actually looks like in terms of code
private Vector3 CustomLerp(Vector3 a, Vector3 b, float t)
{
return a * (1 t) + b * t;
}
}

Using the easing functions script below (Click on view raw to see full script), you can ease the t value.
Which you would write like this: Vector3.Lerp(pointA, pointB, Easing.Quadratic.InOut(t)); This will make the movement of the object very smooth as displayed below.

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

Show hidden characters

*/
public delegate float EasingFunction(float k);
public class Easing
{
public static float Linear (float k) {
return k;
}
public class Quadratic
{
public static float In (float k) {
return k*k;
}
public static float Out (float k) {
return k*(2f k);
}

PLUGIN TO MAKE IT EASY: DOTween

Personally when I’m working I don’t like to spend more time then necessary on movement code. Preferably I move a object within a single line of code.
This is why I like to use easing libraries. DoTween is my favourite so far, and I implement it in almost any game I develop for. Including MASKED, Tiny Gems and BOXKILL. It won’t be used in any of the templates I put on the asset store. This is because it adds complexity for the users.

Aside from moving objects it also helps with scale, rotation, fading of canvas groups. And many other things.
So I definitely reccomend it to take a look. They also have a free version of the plugin available with less features.

As an example, I’ve written the same code as above, but then in DOTween. As you can see it requires less code to get the same results.
It also has the benefit that you don’t have to use many Update() loops in your game, which results in less overhead.

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

Show hidden characters

using DG.Tweening;
using UnityEngine;
public class DoTweenLerpExample : MonoBehaviour
{
[SerializeField] private Vector3 pointA = new Vector3(2, 0, 0);
[SerializeField] private Vector3 pointB = new Vector3(2, 0, 0);
[SerializeField] private float speed = 1;
private void Start()
{
transform.position = pointA;
Tweener tweener = transform.DOMove(pointB, speed);
tweener.SetEase(Ease.InOutQuad);
tweener.SetLoops(int.MaxValue, LoopType.Yoyo);
}
}

Moving an object in Unity can be very straightforward.

It typically involves modifying the properties of an object’s Transform component, which is used to manage a game object’s scale, rotation and position in the world.

However, there are many different ways you can do that…

And while most methods of moving an object in Unity involve modifying the object’s Transform in some way, the exact method you use will vary depending on the type of movement you want to create.

But don’t worry, because in this article, you’ll learn how and when to use each of the different methods for moving an object in Unity, so that you can use the one that’s right for your project.

Here’s what you’ll find on this page:

  • How to move an object in Unity
    • How to use Transform Translate in Unity
    • How to move an object with the keyboard in Unity
    • How to move an object, relative to the camera
  • How to move an object to a position in Unity
    • How to move an object to a position at a set speed (using Move Towards)
    • How to move an object to a position in a set time (using Lerp)
    • How to move an object to a position using animation
  • How to move an object using physics

Let’s get started.

Moving Objects in Unity explained (video)

For a general overview of how to move objects in Unity try my video, or continue to the full article below.



How to move an object in Unity

The most straightforward method of changing an object’s position in Unity is to set it directly, which will instantly move it to a new vector 3 position in the world.

This works by setting the Position property of an object’s Transform component to a new position.

Like this:

// Moves an object to the set position
transform.position = new Vector3(10, 0, 5);

Or you can add a vector to an object’s position, to move it by a set amount in a specific direction.

Like this:

// Moves an object up 2 units
transform.position += new Vector3(0, 2, 0);

Which looks like this:

Visualisation of instant movement in Unity

Adding a vector to an object’s position moves it by that amount.

It’s possible to modify the properties of an object’s Transform from a script that’s attached to it by using the Transform Property:

Transform myTransform = transform;

The Transform property, which is typed with a lower case ‘t’, allows you to reference the Transform component of an object from a script that’s attached to it, without getting a reference to it first.

Which is useful, as it allows you to easily reference, or change, an object’s own position from a script. 

Like this:

Vector3 myPosition = transform.position;

Modifying a Transform’s position is the most straightforward method of creating movement in Unity.

Either by modifying it directly, over time, or by using the Translate function which allows you to move an object in a specific direction. 

How to use Transform Translate in Unity

The Translate function in Unity moves an object by a set amount, relative to its current position and orientation.

Like this:

void Start()
{
    // Moves the object forward two units.
    transform.Translate(0,0,2);
}

This is different to simply adding a vector to the object’s position, which would move it relative to world space, while Translate will, by default, move an object relative to its own local space.

This means that, when using Translate, passing in a forward vector will move the object in the direction of its blue axis, the Z-Axis.

When it’s called once, Translate moves an object by a set amount one time.

However, by calling it every frame, it’s possible to create continuous movement.

Like this:

void Update()
{
    // Moves the object forward two units every frame.
    transform.Translate(0,0,2);
}

However, there’s a problem with this method.

Because framerates vary between devices and, because each frame often takes a different amount of time to process than the last, the speed of an object’s movement would change depending on the framerate when moving an object in this way.

Instead, multiplying the movement amount by Time.deltaTime, which is the amount of time since the last frame, creates consistent movement that’s measured in units per second.

Like this:

void Update() 
{
    // Moves the object forward at two units per second.
    transform.position = new Vector3(0,0,2) * Time.deltaTime; 
}

Which looks like this:

Visualisation of speed-based movement in Unity

Adding a scaled vector over time creates movement.

This works fine, however, it can sometimes be more convenient to manage movement direction and speed separately, by using a Unit Vector to determine the direction and a separate float value to control the speed.

Like this:

public float speed = 2;
void Update()
{
    // Moves the object forward at two units per second.
    transform.Translate(Vector3.forward * speed * Time.deltaTime);
}

This has the same effect as manually typing out the vector, except that the speed is now separate and can easily be changed.

In this example, Vector3.forward is shorthand for (0,0,1) which is the forward direction in world space.

Multiplying Vector3.forward by the speed value, in this case 2, creates the vector (0,0,2) which, when multiplied by Delta Time, creates a forward movement of two units per second.

The result is the same as when manually typing out the vector, except that the speed is now separate and can easily be controlled.

Direction vectors in Unity

A normalised vector, or unit vector, in Unity is simply a vector with a length of 1 that describes a direction. For example the unit vector (0,0,1) describes the forward direction in world space.

Normalised vectors can be extremely useful for calculating distance and speed.

For example, you could multiply a unit vector by 10 to get a position that’s ten units away in a certain direction.

Or you can multiply a vector by a speed value and by Delta Time to create movement at an exact speed in units per second.

While you can type unit vectors manually, you’ll find a number of shorthand expressions for common directional vectors in the Vector 3 class.

For example:

Vector3.forward   // (0,  0,  1)
Vector3.back      // (0,  0,  -1)
Vector3.up        // (0,  1,  0)
Vector3.down      // (0,  -1, 0)
Vector3.right     // (1,  0,  0)
Vector3.left      // (-1, 0,  0)

These relate to common directions in world space, however, it’s also possible to get a normalised direction vector relative to an object’s local position and rotation.

Like this:

transform.forward  // object forward
-transform.forward // object back
transform.up       // object up
-transform.up      // object down
transform.right    // object right
-transform.right   // object left

These can be extremely useful for creating object relative movement.

Such as moving an object forward in the direction that it’s facing.

Like this:

public float speed = 2;
void Update()
{
    // Moves an object forward, relative to its own rotation.
    transform.position += transform.forward * speed * Time.deltaTime;
}

In this case, the object is still moving forward at a speed of two units per second.

The difference is that the direction is based on the object’s orientation, not the world. Which means that if the object rotates, it’ll turn as it moves.

However…

While using a Transform’s local directions can be useful for getting the orientation of a specific object, some functions already operate in local space by default.

Such as the Translate function which, by default, applies movement relative to the object’s local position and orientation, unless you set otherwise.

Which means that, if you use transform.forward with the Translate function, you’ll get a compounded effect, where turning the object throws off its forward vector.

Creating object-relative movement in this way can be useful for adding player controls, where the player can move an object forward, backwards or sideways using input axes, such as from the keyboard.

How to move an object with the keyboard in Unity

To move an object with the keyboard, or with any other input device, simply multiply the direction of movement you want to apply, such as forward, for example, by the Input Axis you want to use to control it.

In Unity, when using the default Input Manager, you’ll find an Input Axis for Horizontal and Vertical movement already set up and mapped to the WASD keys and arrow keys on the keyboard.

  • Input in Unity made easy (a complete guide to the new system)

Each axis returns a value between -1 and 1, which means that you can use the value that’s returned to create a movement vector.

Like this:

public float speed = 2;
void Update()
{
    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");
    Vector3 movement = new Vector3(x, 0, z);
    transform.Translate(movement * speed * Time.deltaTime);
}

This allows you to create object-relative movement controls using the keyboard or any other input device.

Which looks like this:

Visualisation of object relative keyboard movement in Unity

The Horizontal and Vertical input axes can be used to create movement control.

Even movement controls with Clamp Magnitude

When moving an object using horizontal and vertical axes it’s possible to create diagonal movement that is faster than the speed of movement of a single axis.

This is because the length of the vector that’s created from a forward vector of 1 and a sideways vector of 1 is longer than either one on their own, at around 1.4.

Which means that holding forward and right on a keyboard, for example, would move the player 1.4 times faster than just moving forwards or sideways alone, causing uneven 8-way movement.

So how can you fix it?

One option is to normalise the vector, like this:

Vector3 movement = new Vector3(x, 0, z).normalized;

However, while this does work, it means that the length of the vector is always one, meaning that any value less than one, such as analogue movements, or the gradual acceleration that Unity applies to digital axis inputs, is always rounded up to one, no matter what.

This might not be a problem for your game if, for example, you’re using the Raw Input values and are deliberately creating tight digital controls.

Otherwise, to also support values that are lower than 1, you can limit the length of the vector instead, using Clamp Magnitude.

Like this:

public float speed = 2;
void Update()
{
    float x = Input.GetAxis("Horizontal");
    float z = Input.GetAxis("Vertical");
    Vector3 movement = new Vector3(x, 0, z);
    movement = Vector3.ClampMagnitude(movement, 1);
    transform.Translate(movement * speed * Time.deltaTime);
}

This will limit the length of the vector to one, while leaving lower values intact, allowing you to create analogue 8-way movement that’s even in all directions.

The Translate function creates movement that’s relative to the Transform component that it’s called from.

However, you may not always want to create player-relative movement.

So how can you move an object in a direction that’s relative to a different object, such as the camera, for example?

How to move an object, relative to the camera

It’s possible to move an object relative to the position of the camera in Unity by using the camera’s forward vector in place of the object’s forward vector.

Like this:

public float speed = 2;
void Update()
{
    Transform camTransform = Camera.main.transform;
    Vector3 forwardMovement = camTransform.forward * Input.GetAxis("Vertical");
    Vector3 horizontalMovement = camTransform.right * Input.GetAxis("Horizontal");
    Vector3 movement = Vector3.ClampMagnitude(forwardMovement + horizontalMovement,1);
    transform.Translate(movement * speed * Time.deltaTime, Space.World);
}

Because the movement is relative to the camera’s position, the Relative To parameter in the Translate function needs to be set to World Space for this to work.

However, there’s a problem…

The forward vector of the camera may, in some cases, be facing at an angle, down towards the player, meaning that any movement that’s applied will also push downwards, instead of along a flat plane, as you might expect.

To fix this, you’ll need to manually calculate the direction between the camera and the object, while leaving out any rotation that you want to ignore. 

To calculate a direction, all you need to do is subtract the position of the origin from the position of the target and then, normalise the result.

Like this:

Vector3 direction = (transform.position - Camera.main.transform.position).normalized;

To ignore the difference in height between the camera and the object it’s looking at, simply create a new Vector 3 that replaces the camera’s height with the object’s instead.

Like this:

Transform camTransform = Camera.main.transform;
Vector3 camPosition = new Vector3(
    camTransform.position.x, 
    transform.position.y, 
    camTransform.position.z);
Vector3 direction = (transform.position - camPosition).normalized;

This will return a direction that is looking towards the object, but isn’t looking up or down.

You can then use the corrected direction that’s created to calculate movement that’s relative to the camera on a flat plane.

Like this:

public float speed = 2;
void Update()
{
    Transform camTransform = Camera.main.transform;
    Vector3 camPosition = new Vector3(camTransform.position.x, transform.position.y, camTransform.position.z);
    Vector3 direction = (transform.position - camPosition).normalized;
    Vector3 forwardMovement = direction * Input.GetAxis("Vertical");
    Vector3 horizontalMovement = camTransform.right * Input.GetAxis("Horizontal");
    Vector3 movement = Vector3.ClampMagnitude(forwardMovement + horizontalMovement, 1);
    transform.Translate(movement * speed * Time.deltaTime, Space.World);
}

Which looks like this:

Visualisation of camera relative movement in Unity

You can create camera relative movement by using the camera’s forward direction in place of the object’s.

By understanding the relative direction of an object, it’s possible to create any kind of movement control that you want.

However, a lot of the time, you may want to move an object in a different way, that’s not directly controlled by the player.

For example, moving an object to a set position or towards another object.

How to move an object to a position in Unity

Generally speaking, there are two different ways to move an object into a specific position.

  1. By speed, where the object moves towards a target at a specific speed,
  2. By time, where the movement between the two points takes a specific amount of time to complete.

The method you use will depend on how you want to control the object’s movement, by time or by speed.

Here’s how both methods work…

How to move an object to a position at a set speed (using Move Towards)

It’s possible to move an object towards another object or a specific position in the scene using the Move Towards function.

Move Towards is a function of the Vector 3 Class that will modify a Vector 3 value to move towards a target at a set speed without overshooting.

Which works great for moving an object towards a position in the world at a speed you can control.

Like this:

public Vector3 targetPosition;
public float speed=10;
void Update()
{
    transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
}

The movement can also be smoothed, by using the Smooth Damp function, which eases the movement as it starts and ends.

Like this:

public Vector3 targetPosition;
public float smoothTime = 0.5f; 
public float speed = 10;
Vector3 velocity;
void Update()
{
    transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime, speed);
}

This works by setting the position of the object to the Vector 3 result of the Smooth Damp function, passing in a target, the current position and a reference Vector 3 value, which the function uses to process the velocity of the object between frames.

This can be useful for smoothed continuous movement, where the target position may change from one moment to the next such as when following the player with a camera.

Such as in this example of a smooth camera follow script using Smooth Damp:

public Transform player;
public float cameraDistance = 5;
public float cameraHeight = 3;
public float smoothTime = 0.5f;
public float speed = 10;
Vector3 velocity;
void Update()
{
    transform.LookAt(player.transform);
    Vector3 offset = (Camera.main.transform.position - player.position).normalized * cameraDistance;
    Vector3 targetPosition = player.position + offset;
    targetPosition.y = cameraHeight;
    transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime, speed);
}

In this example, the camera will smoothly move towards the player and turn to face them, while keeping at a height of 3 units and trying to stay at a distance of 5 units away.

Move Towards works great as a way to move an object towards a position dynamically.

This is because the movement is speed-based, and can be controlled even if the target position moves or is unknown.

However, there are many times where you may simply want to move an object to a known position over a set period of time.

Such as moving a platform, or opening a door.

So how so you create time-based movement in Unity?

How to move an object to a position in a set time (using Lerp)

Lerp, or Linear Interpolation, is used to find a value between a minimum and maximum based on a position value, ‘t’, which is a float between zero and one.

The value that’s returned depends on the value of t where, if t is 0 the minimum value is returned, while 1 returns the maximum value. 

Any other value in-between 0 and 1 will return a representative value between the minimum and maximum ends of the scale.

float lerpedValue = Mathf.Lerp(float minValue, float maxValue, float t);

Typically, Lerp is used to change a value over a period of time, by incrementing t every frame to return a new value on the scale.

This can be used to change a colour, fade an audio source or move an object between two points.

  • The right way to use Lerp in Unity (with examples)

It works by passing in the amount of time that has elapsed during the Lerp, divided by the total duration. This returns a 0-1 float that can be used for the t value, and allows you to control the length of the Lerp movement by simply choosing how long you’d like it to take.

Like this:

float timeElapsed;
float lerpDuration = 3;
float lerpedValue;
void Update()
{
  if (timeElapsed < lerpDuration)
  {
    lerpedValue = Mathf.Lerp(0, 100, timeElapsed / lerpDuration);
    timeElapsed += Time.deltaTime;
  }
}

Vector3.Lerp works in the same way except that, instead of returning a float, it returns a point in the world between two others, based on the t value.

This can be useful for moving an object between two different positions, such as a door with an open and closed state.

Like this:

public float openHeight = 4.5f;
public float duration = 1;
bool doorOpen;
Vector3 closePosition;
void Start()
{
    // Sets the first position of the door as it's closed position.
    closePosition = transform.position;
}
void OperateDoor()
{
    StopAllCoroutines();
    if (!doorOpen)
    {
        Vector3 openPosition = closePosition + Vector3.up * openHeight;
        StartCoroutine(MoveDoor(openPosition));
    }
    else
    {
        StartCoroutine(MoveDoor(closePosition));
    }
    doorOpen = !doorOpen;
}
IEnumerator MoveDoor(Vector3 targetPosition)
{
    float timeElapsed = 0;
    Vector3 startPosition = transform.position;
    while (timeElapsed < duration)
    {
        transform.position = Vector3.Lerp(startPosition, targetPosition, timeElapsed / duration);
        timeElapsed += Time.deltaTime;
        yield return null;
    }
    transform.position = targetPosition;
}

In this example, I’ve used a coroutine to move the door object up by a set distance from the door’s starting position, whenever the Operate Door function is called.

Which looks like this:

Visualisation of a door being opened with Lerp

Lerp can be used to move an object between two states, such as the open and closed positions of a door.

This creates a linear movement from one position to another, however, it’s also possible to smooth the Lerp’s movement using the Smooth Step function.

This works by modifying the t value with the Smooth Step function before passing it into Lerp.

Like this:

float t = Mathf.SmoothStep(0, 1, timeElapsed / moveDuration);

This will ease the movement of the object at the beginning and end of the Lerp.

How to move an object to a position using animation

Depending on how you’d like to control the movement of objects in your game, it can sometimes be easier to simply animate the object you’d like to move.

This typically involves modifying properties of an object and storing them in Keyframes, which are then smoothly animated between over time.

For example, you could use animation to move an object between two points, such as a floating platform.

This would need three Keyframes to work, one for the starting position, another for the platform’s end position and a final Keyframe to return the platform to its original position, looping the animation.

To animate an object you’ll need to add an Animator and an Animation Clip, which you can do from the Animation window.

Add an Animator dialogue in Unity

Next, select a position on the Animation Timeline, this will be the position of the 2nd Keyframe, when the platform is furthest away..

Animation Timeline selection in Unity

Assuming that, at zero seconds, the platform is at its starting position, this will be the halfway point of the animation which, in this case, is 5 seconds.

Next, enable Keyframe Recording by clicking the record button:

Enable keyframe recording

While Keyframe Recording is enabled, any changes you make to an object will be saved to a Keyframe at that timeline position, such as changing its position:

Screenshot - Recording transform changes to Keyframe

Create a final Keyframe at ten seconds, setting the object’s position to its original values to complete the animation (remembering to disable Keyframe Recording when you’re finished).

Animation Timeline selection in Unity with Keyframe Recording enabled

The end result is a platform that moves smoothly, and automatically, between its Keyframe positions.

These methods work well for creating controlled precise movements in Unity.

But, what if you don’t want to control an object’s movement precisely?

What if you’d rather push, pull or throw an object, to create movement using physical forces instead?

How to move an object using physics

Most rendered objects in Unity have a Collider component attached to them, which gives them a physical presence in the world.

However, an object with only a Collider is considered to be static, meaning that, generally speaking, it’s not supposed to move.

To actually move an object under physics simulation, you’ll also need to add a Rigidbody component to it, which allows it to move, and be moved, by physical forces, such as gravity.

You can also move a physics object by applying force to its Rigidbody using the Add Force function.

Like this:

Rigidbody.AddForce(Vector3 force);

This works in a similar way to the Translate function except that the vector you pass in is a physical force, not a movement amount.

How much the object moves as a result will depend on physical properties such as mass, drag and gravity.

There are two main ways to apply physical force on an object.

You can either apply force continuously, building momentum and speed over time, or all at once in an impulse, like hitting an object to move it.

By default, the Add Force function applies a continuous force, like a thruster gradually lifting a rocket.

Like this:

public Rigidbody rb;
public float forceAmount = 10;
void FixedUpdate()
{
    rb.AddForce(Vector3.up * forceAmount);
}

Notice that I’ve used Fixed Update, and not Update, to apply the force to the object.

This is because Fixed Update is called in sync with the physics system, which runs at a different frequency to Update, which is often faster and can vary from frame to frame.

Doing it this way means that the application of force is in sync with the physics system that it affects.

Alternatively, you can also apply force in a single burst, using the Impulse Force Mode.

Like this:

public Rigidbody rb;
public float forceAmount = 10;
void Start()
{
    rb.AddForce(Vector3.up * forceAmount, ForceMode.Impulse);
}

This will apply an amount of force to an object all at once:

Visualisation of the Add Force function in Unity

Add Force can be used to push objects gradually, or apply force in a single hit, like this.

Which can be useful for faster, more explosive movements, such as making an object jump.

  • How to jump in Unity (with or without physics)

Now it’s your turn

How are you moving objects in your game?

Are you moving them using their Transform components?

Or are you moving them with physics?

And what have you learned about moving objects in Unity that you know others will find helpful?

Whatever it is, let me know by leaving a comment.

Get Game Development Tips, Straight to Your inbox

Get helpful tips & tricks and master game development basics the easy way, with deep-dive tutorials and guides.

My favourite time-saving Unity assets

Rewired (the best input management system)

Rewired is an input management asset that extends Unity’s default input system, the Input Manager, adding much needed improvements and support for modern devices. Put simply, it’s much more advanced than the default Input Manager and more reliable than Unity’s new Input System. When I tested both systems, I found Rewired to be surprisingly easy to use and fully featured, so I can understand why everyone loves it.

DOTween Pro (should be built into Unity)

An asset so useful, it should already be built into Unity. Except it’s not. DOTween Pro is an animation and timing tool that allows you to animate anything in Unity. You can move, fade, scale, rotate without writing Coroutines or Lerp functions.

Easy Save (there’s no reason not to use it)

Easy Save makes managing game saves and file serialization extremely easy in Unity. So much so that, for the time it would take to build a save system, vs the cost of buying Easy Save, I don’t recommend making your own save system since Easy Save already exists.

В данной статье будут приведены примеры кода и их описания.

Два основных компонента у объекта в Unity3D — это Transform и GameObject.

GameObject

GameObject — основа, контейнер, который содержит в себе все компоненты любой объект в Unity3D. Чтобы удалить, к примеру, игровой объект — удалять нужно именно GameObject этого объекта. Для доступа к GameObject — используется переменная, которая присутствует по умолчанию в любом скрипте, унаследованном от MonoBehaviour (то есть в любом скрипте, созданном через Unity3D).

Получение ссылки на игровой объект

var myGo = gameObject; // мы получили ссылку на GameObject объекта

// однако возможно использовать напрямую через gameObject

Данным способом можно из одного скрипта получить ссылку на другие игровые объекты и управлять ими, их дочерними объектами, а также их компонентами.

Уничтожение игрового объекта

Destroy(gameObject); // уничтожает данный объект со сцены

Данным способом можно удалить игровой объект.

Активация/деактивация игрового объекта

gameObject.SetActive(false); // выключает данный объект (и все его дочерние)

gameObject.SetActive(true); // включает данный объект (и все его дочерние)

Деактивация объекта аналогична снятия галочки инспекторе Unity3D, которая обведена красным цветом на скриншоте ниже.

ul0_setActiveFalse

Деактивация элемента деактивирует также все его дочерние объекты и останавливает выполнение в их скриптов.

Добавление новых компонентов и скриптов игровому объекту

gameObject.AddComponent<BoxCollider>(); // добавляет к данному объекту компонент BoxCollider

gameObject.AddComponent<Listener>(); // добавляет к данному объекту скрипт Listener

Таким образом можно добавить абсолютно любой компонент, либо скрипт, который можно добавить в редакторе Unity3D.

Получение доступа к компоненту игрового объекта

var objectBoxCollider = gameObject.GetComponent<BoxCollider>(); // получение ссылки на компонент BoxCollider

Таким же образом можно получить доступ к любому компоненту игрового объекта.

Переименование игрового объекта. Считывание имени объекта

gameObject.name = «ObjectNewName»; // меняем имя объекта

var objectName = gameObject.name; // считываем имя объекта

Сделать объект статичным

gameObject.isStatic = true; // делаем объект статичным

var isObjectStatic = gameObject.isStatic; // считываем — является ли объект статичным

Данный код аналогичен установке/снятию галочки в редакторе Unity3D (на скрине ниже).

ul0_setStatic

Установить слои игровому объекту, а также считать их

gameObject.layer = LayerMask.GetMask(new[] {«Environment», «Tree»}); // устанавливает слой

var objectLayer = gameObject.layer; // получает числовое представление слоев, к которым относится объект

Установить тэг игровому объекту, а также его считывание

gameObject.tag = «newTag»; // устанавливает тэг объекту

var objectTag = gameObject.tag; // считывает тэг объект

Transform

С трансформом всё немного проще — этот компонент не является основой, но тем не менее — является основной и, главное, неотъемлемой частью GameObject’а. Он отвечает за месторасположение объекта на сцене, его «вращении», размерах, а также содержит информацию о дочерних и родительском объектах.

Это единственные компонент, который невозможно удалить из GameObject.

Изменение положение объекта

За положение объекта на сцене отвечает элементы transform.position и transform.localPosition.

Они оба являются переменной типа Vector3 и имеют в себе 3 главных составляющих x,y и z, которые соответствуют координатам в трехмерном пространстве. Следует учитывать, что x, y и z невозможно менять напрямую — они только для чтения. Чтобы добавить единичку к — нужно добавить к самому transform.position новый Vector3, который равен (1,0,0), что добавить к x единицу, а к y и z — нули.

Чем же отличаются transform.position и transform.localPosition?

Их главное (и единственное отличие) заключается в том, что position — показывает и принимает координаты объекта, относительно мировых координат, а localPosition — относительно родительского объекта. Если же игровой объект является «корневым», то есть у него нет родительских объектов, то position и localPosition будут равны.

Движение объекта

Сначала рассмотрим элементарные варианты.

Как мы уже говорили — position (буду далее использовать именно его, так как отличия от localPosition только в том, относительно чего эти координаты) является переменной типа Vector3. Поэтому для его изменения нужно либо прибавить к нему другой вектор, либо вычесть другой вектор, либо заменить его другим вектором.

transform.position += new Vector3(1,0,0); // добавляем к X единицу

transform.position -= new Vector3(1,1,0); // вычитаем из X и Y единицу

transform.position = new Vector3(10,20,30); // устанавливаем объекту координаты 10,20,30 (x,y,z)

Рекомендуется использовать функцию transform.Translate. 

Это уже не переменная, как transform.position — это функция. У неё есть два входящих параметра:

  1. Vector3, который отвечает за то, в каком направлении будет двигаться объект;
  2. Space.Self/Space.World — то, относительно чего будет двигаться игровой объект. Space.Self — аналогичен transform.localPosition, а Space.World — аналогичен transform.position.

Вращение объекта

За вращение объекта отвечает компонент transform.rotation, transform.localRotation и функция transform.Rotate.

Здесь все аналогично transform.position. Кроме одного, несмотря на то, что в редакторе Unity3D Rotation представляет собой Vector3, то есть вращение относительно оси X, оси Y, оси Z.  Но в коде оно представлено в виде кватернионов. Что такое кватернион — отдельная история. И обычно её изучают в вузах. По факту — знание кватернионов не обязательно для разработки игр. К счастью разработчики Unity3D это понимают и сделали две удобные для программистов вещи:

  1. Функция transform.Rotate(Vector3 vector, Space.World(либо Self));
  2. Функция Quaternion.Euler(float x,float y,float z), которая как раз возвращает кватернион;

Меньше слов — больше кода:

var myRotation = Quaternion.Euler(1, 1, 1); //поворачиваем объект по всем трем осям на единицу за такт

transform.rotation *= myRotation; // обращаем внимание, что кватернионы не складывают, а умножают. Делить их нельзя. Поэтому для вычета просто делаем значения вектора отрицательными

Вместо rotation можно применять localRotation, аналогично position.

transform.Rotate(new Vector3(1,0,0),Space.Self); // либо Space.World

Такой подход аналогичен transform.Translate и также является более производительным.

Поиск других объектов на сцене

Есть два подхода поиска объекта на сцене.

  1. GameObject.Find(«имяОбъекта»); Он же «пушка по воробьям». Несмотря на кажущуюся скорость — метод является достаточно прожорливым и при частом использовании на большой сцене может стать большой проблемой. Однако он же самый простой способ (хотя и ненадежный). А ненадежный он потому, что редактор Unity3D позволяет давать одинаковые имена объектам. А GameObject.Find возвращает только один элемент, который он найдет первым.
  2. transform.FindChild(«имяДочернегоОбъекта») — функция возвращает переменную типа transform нужного объекта. Для доступа к GameObject этого объекта особых усилий прилагать не нужно, так как ссылка на него уже содержится в transform (как и ссылка на transform содержится в GameObject’е).

var childTransform = transform.FindChild(«myChild1»);

var childGameObject = childTransform.gameObject;

var anotherTransformLink = childGameObject.transform;

Также можно запрашивать дочерние элементы по их номеру:

var childCount = transform.childCount;

for (var i = 0; i < childCount; i++)

{

   Debug.Log(transform.GetChild(i).name);

}

Также дочерний элемент может запросить родительский, а также родительский родительского и так далее:

var myParent = transform.parent;

var rootObject = transform.parent.parent.parent;

В следующих статьях будет информация о том, что такое private, public, static, отправление сообщений игровым объектам.

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.

vector3 newpos= new vector3(0,10,0);
Void Start()
{
transform.position= newpos;
}

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.

quaternion rot;
float xrot;
float yrot;
float zrot;
void Start()
{
rot=transform.rotation;
xrot=rot.x;
yrot=rot.y;
zrot=rot.z;
}
Void Update()
{
xrot+=5;
rot.x=xrot;
transform.rotation=rot;
}

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.

Понравилась статья? Поделить с друзьями:
  • Как изменить touch id на iphone 7
  • Как изменить title через js
  • Как изменить system product name
  • Как изменить title категории woocommerce
  • Как изменить system ini