There is a way to set a max to the resultant force in a object ?
Using as example my project: I wanted to control my camera (in game) through de "w,a,s,d" keys, so I used the "add.Force" to make it move:
public float speed;
public float olhada;
private Rigidbody rb;
void Start () {
rb = GetComponent<Rigidbody>();
}
void FixedUpdate () {
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rb.AddForce(movement * speed);
}
, but a issue that I saw is that it continue to add more and more force to the camera so it reaches lightspeed if you hold the keys for to much. So to solve it I thought "Why I dont use "Transfor.position" instead?", and then I made this:
public float speed;
public float olhada;
private Rigidbody rb;
void Start () {
rb = GetComponent<Rigidbody>();
}
void FixedUpdate () {
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
transform.position += movement;
}
,which solved the problem of the camera getting to fast, but , instead of "Add.Force", it wasn't a force, so colisions didn't stop the camera to pass through wall and, basicly, everything. So, after these tries I saw that the "Add.Force" method was better but I had no idea of how I could make a limit to the camera move like in the "Transfor.position". And here comes my question:
There is a way to set a max to the resultant force in a object ?
(Sorry if my description got to big (and borring), but I wanted to give the maximum of details I could)
Answer by kalen_08 · Jul 20, 2018 at 12:59 AM
I think what you want to do is check if it's at a certain speed then not add anymore force...
//maxSpeed would be a variable you add...
if (rigidbody.velocity.magnitude < maxSpeed)
{
//forceToAdd is whatever force you're adding
rigidbody.AddForce(forceToAdd);
}
//or Option #-----------------------------
rigidbody.AddForce(forceToAdd);
if (rigidbody.velocity.magnitude > maxSpeed)
{
var direction = rigidbody.velocity.normalized;
rigidbody.velocity = direction * maxSpeed;
}
Thanks, that's exactly what I intended to ask/do ! I apreciate the help! ; )
you're welcome :) could I ask though that you accept my answer?
Your answer
Follow this Question
Related Questions
How to transform position to left? 1 Answer
how do i make player die when falling certain height? 3 Answers
how can i limit position between 2 object ?? 1 Answer
How does physics work in this code? 0 Answers
Making Force Grip/Grab 0 Answers