# Question 2D player Movement

Discussion in 'Getting Started' started by fshakeel9233, Aug 13, 2023.

1. ### fshakeel9233

Joined:
Jun 17, 2022
Posts:
3
Kindly help me with this player movement with left-right buttons

File size:
3.8 MB
Views:
49
2. ### AngryProgrammer

Joined:
Jun 4, 2019
Posts:
490
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.
Code (CSharp):
1. using UnityEngine;
2.
3. public class PlayerMovement : MonoBehaviour
4. {
5.     public float moveSpeed = 5.0f; // Speed of movement
6.     public float rotationRadius = 2.0f; // Radius of the semicircle
7.     public bool limitToHalfCircle = true; // Flag to limit movement to half circle
8.
9.     private float angle = 0.0f; // Current angle on the semicircle
10.     private Vector2 centerPoint; // Center point of the semicircle
11.
12.     private void Start()
13.     {
14.         // Set the initial center point of the semicircle to the player's position
15.         centerPoint = transform.position;
16.     }
17.
18.     private void Update()
19.     {
20.         // Get input from the player
21.         float horizontalInput = Input.GetAxis("Horizontal");
22.
23.         // Update the angle on the semicircle based on player input
24.         angle += horizontalInput * moveSpeed * Time.deltaTime;
25.
26.         // Check if we want to limit the movement to half circle
27.         if (limitToHalfCircle)
28.         {
29.             // Limit the angle to the range of -PI/2 to PI/2
30.             angle = Mathf.Clamp(angle, -Mathf.PI / 2.0f, Mathf.PI / 2.0f);
31.         }
32.
33.         // Calculate the player's position on the semicircle
34.         Vector2 newPosition = new Vector2(
35.             centerPoint.x + Mathf.Cos(angle) * rotationRadius,
36.             centerPoint.y + Mathf.Sin(angle) * rotationRadius
37.         );
38.
39.         // Move the player object to the new position
40.         transform.position = newPosition;
41.     }
42. }
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.

3. ### fshakeel9233

Joined:
Jun 17, 2022
Posts:
3
Thank you so much. it's working