- Home /
Functions and Rigibodies
Modern games lag terribly. I'm aiming for a great performance. Update is called every frame and FixedUpdate is called every fixed frame. Should rigidbody transforms be changed inside of functions such as this one?
private var hit : RaycastHit;
private var forward : Vector3;
function Update() {
if (Input.GetButtonDown("Fire1"))
RayFire();
}
function RayFire() {
forward = transform.TransformDirection(Vector3.forward);
if (Physics.Raycast(transform.position, forward, hit, range)) {
rigibody.AddForceAtPosition(forward * force, hit.point);
}
}
Yes that's just fine. You can add a force anywhere, you should only modify its position or rotation directly inside FixedUpdate.
Apart from you haven't defined forward, hit and range - but I'm guessing this is just example code?
No - it's adding force - I mean really modify the .position / .localPosition
Answer by dukearena · Nov 19, 2012 at 11:28 AM
Hi Corey All rigidibodies functions should be called from FixedUpdate. The code you wrote is right, but try to rename Update with FixedUpdate like this example:
function FixedUpdate() {
if (Input.GetButtonDown("Fire1"))
Fire();
}
function Fire() {
if (Physics.Raycast (transform.position, forward, hit, range)) {
rigibody.AddForceAtPosition(forward * force, hit.point);
}
}
Remember that FixedUpdate doesn't use Time.deltaTime but Time.fixedDeltaTime
That is totally wrong!!! You can't use Input in FixedUpdate all sorts of weird things happen (you miss up and down presses and movements). You can add a force to a rigidbody anywhere - it's just direct modification of position and rotation you have to avoid outside FixedUpdate.
I'm sorry, this thing of input inside FixedUpdate is totally new for me.. Thanks for the news :D
Yeah - the problem it is that it "kinda" works! The problem is fixed update may be called many times per frame of your game, or never - depending on whether it is catching up with the game or the game is running faster than it!
Input is updated based on real frames so the frame in which a button is pressed may be processed multiple times by FixedUpdate or never. Likewise everything else.
It's a real gotcha.
I have code to change than. So would my original code work?
Your answer
Follow this Question
Related Questions
How to pass function as parameter to function? 1 Answer
assigned function declaration in unity javascript for different types 1 Answer
Creating & accessing a function from a diffrent "OnTriggerEnter" Function 1 Answer
calling a function from another script 2 Answers
What is the difference between InvokeRepeating & Invoke and how can they be used? 1 Answer