Hello, I am prototyping a 2D platforming game for practice. I am working on the player movement and so far I have successfully gotten it to move based on input. However, I am unable to limit the speed. I have tried setting a max speed and changing the velocity to match the max speed if the player’s current velocity exceeds the max speed, but that has not been working. Is there a smooth, clean way to limit the max speed? Can I clamp it? If so, how? I am very new to programming, especially when it comes to 2D physics. Thanks in advanced.
Here is my current script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public float speed;
public float maxSpeed;
public bool onGround;
public Rigidbody2D playerRB;
private void Start()
{
playerRB = gameObject.GetComponent<Rigidbody2D>();
}
private void FixedUpdate()
{
float x = Input.GetAxis("Horizontal");
playerRB.AddForce((Vector2.right * speed) * x);
}
}
Welcome to 2D physics, PresidentPorpise I ran your code against an old one of mine (stripped down to the basics). When I tested yours, it definitely kept increasing in speed (with speed at 10 and maxSpeed at 15). Acceleration was a bit slow.
For some reason mine has sharper acceleration, and won’t accelerate past the set float value. I’m also pretty new, so I’m sure there’s a tutorial that could explain more.
using UnityEngine;
using System.Collections;
public class MyMovement : MonoBehaviour
{
public float maxSpeed = 10f;
private Rigidbody2D rigid2d;
void Start()
{
rigid2d = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
float move = Input.GetAxis("Horizontal");
rigid2d.velocity = new Vector2(move * maxSpeed, rigid2d.velocity.y);
Vector2 movement = new Vector2(move, 0);
rigid2d.AddForce(movement * maxSpeed);
}
}
If you’re interested in clamping values, use Mathf.Clamp. It’s very easy to use, and efficient Good luck on your game