Kindly help me with this player movement with left-right buttons
Finding a solution (not only in Unity) requires describing the problem. What do you see in the example?
- Player left-right input set the game object into half circle movement.
Divide and conquer the problem, what do I need?
- How to capture player left-right input?
- How to translate player input into movement on a circle?
- How to limit player input to move only half circle?
Now you know what you need. You can review your school mathematic knowledge a bit about sin and cos to do it yourself with full understanding or just by using proper questions to get answers right away from the Internet.
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5.0f; // Speed of movement
public float rotationRadius = 2.0f; // Radius of the semicircle
public bool limitToHalfCircle = true; // Flag to limit movement to half circle
private float angle = 0.0f; // Current angle on the semicircle
private Vector2 centerPoint; // Center point of the semicircle
private void Start()
{
// Set the initial center point of the semicircle to the player's position
centerPoint = transform.position;
}
private void Update()
{
// Get input from the player
float horizontalInput = Input.GetAxis("Horizontal");
// Update the angle on the semicircle based on player input
angle += horizontalInput * moveSpeed * Time.deltaTime;
// Check if we want to limit the movement to half circle
if (limitToHalfCircle)
{
// Limit the angle to the range of -PI/2 to PI/2
angle = Mathf.Clamp(angle, -Mathf.PI / 2.0f, Mathf.PI / 2.0f);
}
// Calculate the player's position on the semicircle
Vector2 newPosition = new Vector2(
centerPoint.x + Mathf.Cos(angle) * rotationRadius,
centerPoint.y + Mathf.Sin(angle) * rotationRadius
);
// Move the player object to the new position
transform.position = newPosition;
}
}
Above code works and is limited for movement of the right side of a circle. So you need to find a solution how to get the other 3 half-circle limits.
Thank you so much. it’s working