- Published on
[Unity] Summary of how to move game objects [Translate, Rigidbody, Vector3]
- Authors
- EvelynFull-time IndieDev.I'm Japanese, so please forgive me if my English is strange.
In this article, I'll show you how to move objects using Unity's "transform" and "vector3".
Table of Contents
Moving with transform
transform.Translate()
Translate method is used when you want to move the object with respect to the current position of the object.
If you want to know more details, please refer to the official Unity reference.
Unity documentationNow, copy and paste the following code and try using it (the class name is named Move, so just change it here to the class name you are using).
The object will now move with the arrow keys.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mover : MonoBehaviour
{
[SerializeField] float VerticalPower = 0.1f;
[SerializeField] float HorizontalPower = 0.1f;
Dictionary<string, bool> _moveFlagDict = new Dictionary<string, bool>
{
{"up", false },
{"down", false },
{"left", false },
{"right", false },
};
// Update is called once per frame
void Update()
{
_moveFlagDict["up"] = Input.GetKey(KeyCode.UpArrow);
_moveFlagDict["down"] = Input.GetKey(KeyCode.DownArrow);
_moveFlagDict["left"] = Input.GetKey(KeyCode.LeftArrow);
_moveFlagDict["right"] = Input.GetKey(KeyCode.RightArrow);
}
void FixedUpdate()
{
if (_moveFlagDict["up"])
{
transform.Translate(0f, 0f, VerticalPower);
}
if (_moveFlagDict["down"])
{
transform.Translate(0f, 0f, -VerticalPower);
}
if (_moveFlagDict["left"])
{
transform.Translate(-HorizontalPower, 0f, 0f);
}
if (_moveFlagDict["right"])
{
transform.Translate(HorizontalPower, 0f, 0f);
}
}
}
Notes
This is because the repetition speed of Update() varies depending on the performance of the device, causing the movement speed to be fast on a computer, but slow on a smartphone.
In such a case, you need to use FixedUpdate(). This is a function that is called at regular intervals, so if you use it, the movement speed will be the same on all devices. Be sure to use FixedUpdate() for the movement process.
transform.position
Moves an object by specifying its coordinates. Originally, it is often used to warp an object to a specified location by using something like transform.position = new Vector3(0f, 0f, 0f);.
If you add it to the current coordinates, as in this case, you can move it in the same way as transform.
Time.deltaTime where transform.forward is a vector of the direction the object is facing, and 1f * Time.deltaTime indicates that the process will be performed at a speed of 1 m/s.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mover : MonoBehaviour
{
[SerializeField] float MovementRate = 2f;
void FixedUpdate()
{
Vector3 MoveVal = transform.forward * MovementRate * Time.deltaTime;
if (Input.GetKey("up"))
{
transform.position += MoveVal;
}
if (Input.GetKey("down"))
{
transform.position -= MoveVal;
}
if (Input.GetKey("right"))
{
transform.position += MoveVal;
}
if (Input.GetKey("left"))
{
transform.position -= MoveVal;
}
}
}
Moving with Vector3
Vector3.MoveTowards()
This is used when you want to move towards the specified coordinates.
It is often used when you want to chase a specific target.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Mover : MonoBehaviour
{
[SerializeField] float Speed = 1.0f;
[SerializeField] Vector3 Direction = new Vector3(0f, 10f, 10f);
void Update()
{
float step = Speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, Direction, step);
}
}
Moving with Rigidbody
Rigidbody.AddForce()
This is used to apply physical force to an object to make it move, when you have a Rigidbody component attached to the Cube and want to use physics and acceleration.
GetKey to get the bool type true, and then execute it.
GetAxis("Vertical") to get a float value. GetAxis("Vertical") to get the value of the float, which ranges from -1 to 1.
GetAxis("Horizontal") * speed in the x-axis direction, and Input. ") * speed in the z-axis direction.
FixedUpdate() is often used when using Rigidbody; Update() has a different processing interval depending on the performance of the computer, while FixedUpdate() is constant regardless of performance.
If you don't use FixedUpdate(), the addforce interval will vary from machine to machine, causing the movement speed to change.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class Mover : MonoBehaviour
{
[SerializeField] float Speed = 10.0f;
Rigidbody _rb;
void Start()
{
_rb = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float x = Input.GetAxis("Horizontal") * Speed;
float z = Input.GetAxis("Vertical") * Speed;
_rb.AddForce(x, 0, z);
}
}
Conclusion
What did you think?
Moving game objects is something that must be implemented in game development, isn't it?
I hope you will expand on the contents of this article and create your own unique game.
Thank you for reading to the end.