I am adding game over logic when the player falls out the map. I set the players position to be at the start which in this case is -0.823698401,-12.3304148,-206.559509. I do this to send it back to its position. transform.Translate(-0.823698401f, -12.3304148f, -206.559509f);
But for some reason it still has the velocity from rb.AddForce(Vector3.forward * forwardSpeed * speedMultiplier * Time.deltaTime);
. And I don't really know how to cancel it. Here is the whole script if you need it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public float speed = 100f;
public float forwardSpeed = 100f;
public int speedMultiplier = 5;
public Rigidbody rb;
public TextCustomizer customizer;
private bool onGround = true;
void Update()
{
if (Input.GetKey(KeyCode.Space) && onGround == true)
{
rb.AddForce(Vector3.up * speed);
customizer.AddScore(20);
}
if (transform.position.y < -32) // This block
{
customizer.score = 0;
rb.AddForce(Vector3.zero);
Debug.Log("Velocity is: " + rb.velocity);
Debug.Log("Angular velocity is: " + rb.angularVelocity);
transform.Translate(-0.823698401f, -12.3304148f, -206.559509f);
}
rb.AddForce(Vector3.forward * forwardSpeed * speedMultiplier * Time.deltaTime);
}
void OnCollisionEnter(Collision other)
{
if (other.gameObject.CompareTag("Ground"))
{
onGround = true;
}
}
void OnCollisionExit(Collision other)
{
if (other.gameObject.CompareTag("Ground"))
{
onGround = false;
}
}
}
I was trying to make that game over logic again. I put the rb.AddForce(Vector3.zero); to cancel it out but it did not work. I also tried other methods like using the isKinematic and resetting the velocity and angular.
To cancel the velocity immediately, set the velocity vector to Vector3.zero
.
rb.velocity = Vector3.zero;
This should be the same as adding a force of negative velocity, when using ForceMode.VelocityChange.
rb.AddForce(-rb.velocity, ForceMode.VelocityChange);
Another issue is that Transform.Translate does not set the position.
Moves the transform in the direction and distance of translation.
Instead use Rigidbody.position and assign the desired position.
If you change the position of a Rigibody using Rigidbody.position, the transform will be updated after the next physics simulation step