# why does my player object keep moving to one spot?

Im trying to make a Prototype for a Smash Fangame (that ill ask nintendo permission to make and publish)
and im making a 2d unity controller but the problem is that although it works it keeps going back to its origin in the editor once I let go of the key

here is the code

``````using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Controler : MonoBehaviour
{
public Rigidbody2D Player;

[Range(1f, 5f)]
public float speed = 1;

// Update is called once per frame
void Update()
{
var movement = Input.GetAxis("Horizontal");
transform.position = new Vector3(movement, 0f, 0f) * speed;
}

private void FixedUpdata()
{

}
}
``````

any ideas asto why this is happening?

Before I answer I would ask if you know what would be in “movement”? You seem to think movement contains the position in the world where you want to be but it’s the horizontal input (you read it above) typically ranging from -1 to 1.

You’re setting this transform to be the input -1 to 1 * speed on X and YZ = 0. When you let go of the input it’ll be zero * speed so your position will be (0, 0, 0). At max it will be (-speed, 0, 0) or (speed, 0, 0).

``````transform.position = <somePosition>
``````

so as soon as your movement is 0, as in the horizontal axis is not pressed, your object gets teleported to position (0, 0, 0)

sooo how do i fix this?

``````transform.position += new Vector3(movement, 0f, 0f) * speed;
``````

wait i think its translate

Yes, you’re calculating how much you might want to translate it and can use that but if you do that you’ll need to additionally scale it by Time.deltaTime otherwise you’ll get different speeds relative to frame-rate.

Also, you should absolutely NOT be doing this on a GameObject that uses 2D physics. This is what the Rigidbody2D API is for. If you’re not then that’s fine.

IT WORKS NOW! :)

exactly

translation, and adding a vector to your position is the same thing (as in Translate() or +=)

setting your position to a new position is not a translation, thats where your problem lies (as in =)

@MelvMay What do you mean by I should use the Rigidbody2d API?

As I said, if that GameObject has 2D physics components such as Rigidbody2D on it then it’s that component that controls the Transform, not you so you should use its API. As I said above, if that’s not the case then that’s fine.

Unity has already a framework for physics and movement, that would be Rigidbody for 3D and Rigidbody2D for 2D

instead moving your object by its transform, you move it by applying forces to a Rigidbody.
The main differences:

• Rigidbody will respect Colliders (will never move inside them), while movement by Transform will just teleport into other objects if you dont catch it yourself
• Rigidbody can recieve multiple “movement” forces from several sources, doing that in a Transform would mean that whichever is calculated last overwrites the others