Hi, I’m actually learning Unity and try to create simple game mechanics. I would like to roll a ball to a fixed distance, for example my ball is on a cube1 and have to roll on cube2 and stop.
The following video illustrates what I want to do (just when the ball is moving forward) :
This is what I did, but the ball doesn’t reach the target position and stop before.
public class Movement : MonoBehaviour
{
public float speed;
private Rigidbody rb;
private void Start()
{
rb = GetComponent<Rigidbody>();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.UpArrow))
{
Vector3 pos = rb.transform.position;
Debug.Log(pos.ToString());
pos.x += 1f;
Debug.Log(pos.ToString());
transform.position = Vector3.MoveTowards(rb.transform.position, pos, speed * Time.deltaTime);
}
}
}
Thank you for your help
You’re telling the script to keep moving to the right. In the code you wrote, rb.transform.position is equal to transform.position, so every frame youre taking your own position, and trying to move to that exact same position, but 1 unit to the right.
Do you want to press arrow just once and have it move all the way, or do you want the user to hold it until the ball gets there? You need to describe the logic you want to happen more before we can help you.
You are kinda mixing rigidbody movement and transform movement. If you were to just use RigidBody movement it would look like this:
Transform target;
RigidBody rb;
void Start () {
rb = GetComponent<RigidBody>();
}
void LateUpdate() {
if (Input.GetKeyDown(KeyCode.UpArrow))
HandleMovement ();
}
void HandleMovement () {
Vector3 movePosition = transform.position;
movePosition.x = Mathf.MoveTowards(transform.position.x, target.position.x, speed * Time.deltaTime);
rb.MovePosition(movePosition);
}
From here you only need to assign the target
to
I fixed my problem
float distanceTravelled;
Vector3 lastPosition;
float speed = 2.0f;
bool isMoving;
private void launcheMovement()
{
if (Input.GetKey(KeyCode.UpArrow))
{
isMoving = true;
}
}
private void Movement()
{
if (isMoving)
{
lastPosition = transform.position;
transform.position += Vector3.right * speed * Time.deltaTime;
distanceTravelled += Vector3.Distance(transform.position, lastPosition);
Debug.Log("Distance travelled : " + distanceTravelled);
if (distanceTravelled >= 1.0f)
{
isMoving = false;
distanceTravelled = 0;
}
}
}
private void Update()
{
launcheMovement();
Movement();
}