[Solving] How to clamp rotation on a 2D object

Hello,

I have run into a little problem that is too advanced for me yet. I hoped somebody could hint me to how to solve this issue.

Problem:
Although my game works fine I am unhappy with the freedom of movement that the unity engine provides to the ball. I don’t like that my ball sometimes goes straight to the right or left. In my version of this game this is extra bad because I made it so that the ball and player can pass the sides and pop up on the other side. In other words I wish to limit horizontal movement.

Objective:
I wish to restrict the angle of the ball. (See image: green–> okay, red–> not okay). Luckily my ball is an image and does not rotate by itself.

Now I need to do 3 things:

  1. Determine whether my ball is moving to the right or left (or potentially neither if it moves straight up or down). The only way I can think of doing this is by calculating the current position and comparing that to the position of the previous frame. Are there any better ways/ build in functions?

  2. I need to see what angle the ball is making.

  3. If it is in the red zone it should be (a bit randomly) tweaked so that the angles comes into the green zone. This I found can be done with:
    transform.Rotate (Vector3.forward * X) (where X is the angle you want to rotate the object by.)

Alternatively I could try a clamp on the angle?

Does anyone have an idea how to get closer to achieving the objective? Thanks!

1 Like

Hi @Erik_van_Oosterhout,

I put this together some time ago;

It enables you to determine the point of impact and from that you could determine whether the impact occured on the left or right hand side of the paddle.

Then, based on the length of the paddle, halved, you could then proportion this value to be used to calculate a new vector for the ricochet. So, if it right on the far right end of the paddle, this would be your shallowest angle back out etc.

Thanks for the info! This will help a lot!

I first didn’t see how your code would help, since I don’t want the outward angle to be solely dependent on the position it hit the object, but also on the angle it hits it. But I see now that if you know the location you calculate everything else you need.

My solution for this problem is as follows:

  1. I initialize a vector2 previous_Ball_Position at the start of the game as the ball’s beginning position.
  2. Each time a new object is hit the X and Y position get compared with previous_Ball_Position. Using delta X / delta Y I can determine the angle with which the object is hit.
  3. If the angle is in the green zone, do nothing. Else tweak the value.
  4. The location the object is hit is stored in previous_Ball_Position

This will take me a couple of hours, but I now know how to do it! Thanks! Alot!

1 Like

Glad to hear that this was of use… :slight_smile:

Privacy & Terms