Hello
I am quite new to unity and I am having a problem to move my player.
My goal is to move my player smoothly one unit to the right if I press the right arrow and same to the left. So my player move this way: (x,x,x) to (x+1,x,x) and it continue to move one more unit(s) if I keep the key pressed.
I finally manage to do it with the player transform (and it works exactly as I wanted) but it has problem with collision with other object, so after reading a bit I decide to switch to use its rigidbody instead of changing its transform.
I manage once again to make it work by using rigidBody.MovePosition() and the player move one unit per one unit, halas it move really really fast, about 10 unit when I touch briefly the key, so I want to slow down it’s movement.
The answers I saw on this website about speed change concerns movements in a given direction that were not restrained to a constant distance so I couldn’t use them.
This is my code:
public class PlayerController : MonoBehaviour{
Vector3 pos = Vector3.zero;
Transform tr;
//public float movementspeed = 5.0f;
CharacterController characterController;
Rigidbody rigidBody;
void Start(){
pos = transform.position;
tr = transform;
characterController = GetComponent<CharacterController>();
rigidBody = GetComponent<Rigidbody> ();
}
void FixedUpdate(){
Vector3 delta = Vector3.zero;
if (Input.GetKey(KeyCode.RightArrow) && tr.position == pos)
delta = Vector3.right;
else if (Input.GetKey(KeyCode.LeftArrow) && tr.position == pos)
delta = Vector3.left;
pos += delta;
//transform.position = Vector3.MoveTowards (transform.position, pos, Time.deltaTime * movementspeed);
//characterController.Move(delta);
rigidBody.MovePosition (pos);
}
}
This line was the First I tried that works but it use the transform and it gives bag collisions.
//transform.position = Vector3.MoveTowards (transform.position, pos, Time.deltaTime * movementspeed);
These two are my attempt to use the rigidbody but they both gives a result too fast. I don’t really care between using a classic rigidbody or a charactercontroler as I don’t know which is the most adapted to my grid game.
//characterController.Move(delta);
rigidBody.MovePosition (pos);
I also looked at the Rigidbody.MovePosition doc and it says we can smooth the movement by playing with interpolation and isKinematic but I didn’t see a difference.