The Poorgramming
The Poorgramming
Translate
This method moves the object by translating its position in a specified direction.
csharp
Copy
using UnityEngine;
void Update()
{
float moveX = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
float moveY = Input.GetAxis("Vertical") * speed * Time.deltaTime;
2. Rigidbody2D.MovePosition
This method is used when you want to move a Rigidbody2D component, which is useful for
physics-based movement.
csharp
Copy
using UnityEngine;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
float moveX = Input.GetAxis("Horizontal") * speed * Time.fixedDeltaTime;
float moveY = Input.GetAxis("Vertical") * speed * Time.fixedDeltaTime;
3. Rigidbody2D.velocity
This method directly sets the velocity of the Rigidbody2D, which is useful for continuous
movement.
csharp
Copy
using UnityEngine;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
float moveX = Input.GetAxis("Horizontal") * speed;
float moveY = Input.GetAxis("Vertical") * speed;
This method applies a force to the Rigidbody2D, which is useful for physics-based movement
like jumping or pushing.
csharp
Copy
using UnityEngine;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
float moveX = Input.GetAxis("Horizontal") * speed;
float moveY = Input.GetAxis("Vertical") * speed;
● rb.AddForce applies a force to the Rigidbody2D, which can be used for more dynamic
movement.
csharp
Copy
using UnityEngine;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
● Vector2.Lerp smoothly interpolates between the current position and the target position.
● Camera.main.ScreenToWorldPoint converts the mouse position from screen space to
world space.
6. MoveTowards
This method moves the object towards a target position at a specified speed.
csharp
Copy
using UnityEngine;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
● Vector2.MoveTowards moves the object towards the target position at a constant speed.
Although primarily used in 3D, CharacterController can be adapted for 2.5D games.
csharp
Copy
using UnityEngine;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
float moveX = Input.GetAxis("Horizontal") * speed;
float moveY = Input.GetAxis("Vertical") * speed;
Summary
Each method has its own use case depending on whether you need physics-based movement,
smooth transitions, or simple position updates.