It’s because you’re using Translate to move a rigidbody. Don’t do that. In FixedUpdate(), which is where physics updates happen, set the rigidbody2D.velocity, if you want a constant speed, or use rigidbody2D.AddForce(x,y); if you want a gradual increase.
Try and keep any Input.Get related functions in Update(), as that is when such things are looked up. It will be inconsistent done in FixedUpdate.
Don’t call GameObject.Find() every update, that is very inefficient. If this script is already attached to the “sonic” game object, then all you need is “transform.position” to get the current position of the object this script is attached to. Otherwise, create a “public Transform player” and at Start() make “player = GameObject.Find(“sonic”).transform;”. Then all you need to do to use it in your script is “player.position” to get the current position of that object. Same goes for the camera.
It goes faster because that’s how AddForce() works, it “Adds” force, so it builds on any existing force. If you want it to not go faster than a certain speed, you can use a condition like:
if(x != 0) //If x is not equal to 0, then it must be either greater or less than it, thus we must be pressing a direction, so continue with movement code
{
if(Mathf.Abs(rigidbody2D.velocity.x) < maxSpeed) //If we're less than our maxSpeed, then continue to AddForce
{
rigidbody2D.AddForce(new Vector2(speed * x,0)); //We only need 1 AddForce(), and simply multiply our speed by the "x" direction, so we go the direction being pressed
}
else //else if our velocity has gone past the maxSpeed we want, then we set our velocity back to the maxSpeed before the update ends
{
rigidbody2D.velocity = new Vector2(maxSpeed * x,0);
}
}
Of course, if you don’t want a gradual buildup of speed, you can simply skip AddForce and these conditions, and just straight up use:
rigidbody2D.velocity = new Vector2(speed * x,0);
edit: Oops, left out some small things that made that not work lol, fixed.
Its because you are using Addforce. You are giving a force to the x-axis again and again …
Better you use Rigibody2D.velocity to handle the normal constant movement. Use Addforce for “Single Tasks”, for example a jump from your Charackter.
Right click in your project folder → Create → Physics2D Material
In the Inspector of this Material, you have to set ‘Friction’ to zero.
Afters this, drag the Material to the (Box-)Collider of your Player.