- Home /
Why does the length value become 0 sometimes?
I want to execute certain code when the length differs from prelength by 0.3 or more. But oddly, the length is stored as 0, so the if statement is executed. If you know the cause, let me know.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class GoForward : MonoBehaviour {
public Rigidbody rb;
Vector3 prepos;
Vector3 dir;
Vector3 predir;
float power;
float length;
float prelength;
// Use this for initialization
void Start () {
Debug.Log("Let's start");
rb = GetComponent<Rigidbody>();
prepos = transform.position;
power = 1.5f;
prelength = 0;
length = 0;
}
// Update is called once per frame
void Update () {
dir = transform.position - prepos;
length = dir.magnitude;
rb.AddForce(dir*power);
Debug.Log("length="+length+" dir="+dir);
prepos = transform.position;
predir =dir;
if(prelength-length>0.3){
rb.AddForce(dir*5);
Debug.Log("prelength="+prelength+" length="+length);
//Debug.Log(Time.deltaTime+"충돌발생!!!!!!");
}
prelength =length;
}
}
Answer by qobion · Oct 12, 2018 at 06:18 AM
Physics using FixedUpdate(), so when you adding force to Rigidbody in Update() unity waits for FixedUpdate and then adding force. Im sure using FixedUpdate() instead Update() will fix your problem
Can I use InvokeRepeating ins$$anonymous$$d FixedUpdate?
Your answer
Follow this Question
Related Questions
Making an integer minimum value 0 2 Answers
GameObject Rotation Jumps in value 1 Answer
Variables and ranges in javascript 2 Answers
Animation not recognizing small differences 0 Answers
Expression denotes a 'type' 2 Answers