Clamping not working

Godot Version 3.5

Question

I am trying to create the classic ping-pong game. Everything seems good except for the paddle.

A brief about paddle : It is a staticbody2d. That moves up and down.

Here’s the code i wrote:

using Godot;
using System;

public class StaticBody2D2 : StaticBody2D
{
private int speed = 400;
public Vector2 ScreenSize;
// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
ScreenSize = GetViewportRect().Size;
}

// // Called every frame. ‘delta’ is the elapsed time since the previous frame.
public override void _Process(float delta)
{
var velocity = Vector2.Zero;
if (Input.IsActionPressed(“ui_up”))
{
velocity.y -= 100;
}
if (Input.IsActionPressed(“ui_down”))
{
velocity.y += 100;
}

    Position += velocity * (float)delta;
     Position = new Vector2(
        x: Mathf.Clamp(Position.x, 0, ScreenSize.x),
        y: Mathf.Clamp(Position.y, 0, ScreenSize.y)
     );

}
}

The clamping only seems to be working at the top but at the bottom, the paddle slides out off the screen.

Also i’ve added staticbodies as wall around the game. The ball which is a kinematicbody2d seems to be bouncing perfectly off the wall.

Can you help clamping the paddle inside of the playscreen.

Also btw i’m using godot.3.5.

sorry

You should explain how it’s not working, otherwise it’s hard to help you. An example of your code and what you’re expecting to happen + what actually happens.

But, probably you’re not assigning the result :slightly_smiling_face: Clamp doesn’t change the variable passed in but returns a new one. so instead of clamp(0, 1, value) to value = clamp(0, 1, value)

3 Likes

sorry yo i left to remove the symbols

1 Like

Ah it happens

Could be caused by the window stretch mode. Did you try printing the position.Y value so you can see whatabouts it is when it’s not getting clamped? and also check what the ScreenSize.Y is

1 Like

Thanks dude, it worked.

When i saw the values at screensize.y and the position at which my paddle was sitting on screen. I came to a conclusion that my screensize.y was off by 100 because of which my paddle was always going below the game screen therefore I tweaked the clamping at y and it did the trick.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.