I found the mistake in my code - I needed to set 'launchBall' to false in the FixedUpdate function. Woops.
Breakout Game Tutorial Question - Putting addForce in FixedUpdate makes the ball fly out of the screen at high speed?
Hey guys!
After completing this tutorial : https://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/creating-a-breakout-game , I've tried to re-implement the physics of the ball in FixedUpdate(), and the ball seems to behave quite differently than the implementation in the tutorial.
I'm really interested to find out why... Here's my code for the ball GameObject, for example :
using UnityEngine;
using System.Collections;
public class Ball : MonoBehaviour {
public float ballInitialVelocity = 600f;
private Rigidbody rb;
private Vector3 paddlePos;
private float ballVelocity;
private float chargeRate = 90f;
private bool charging = false;
private bool launchBall = false;
private Vector3 mousePosition;
void Awake () {
rb = GetComponent<Rigidbody>();
}
void Update ()
{
if (Input.GetButtonDown("Fire1") && GM.instance.ballInPlay == false)
{
ballVelocity = ballInitialVelocity;
//Mathf.Clamp(ballVelocity, 0, 1000f)
charging = true;
}
if (charging == true)
{
print("Before : " + ballVelocity);
ballVelocity = Mathf.Clamp(ballVelocity + (chargeRate * Time.deltaTime), 0, 800f);
print("After : " + ballVelocity);
}
if (Input.GetButtonUp("Fire1") && charging == true){
launchBall = true;
}
}
void FixedUpdate()
{
// Launch the ball
if (launchBall == true)
{
charging = false;
transform.parent = null;
GM.instance.ballInPlay = true;
rb.isKinematic = false;
rb.AddForce(new Vector3(ballVelocity, ballVelocity, 0));
ballVelocity = ballInitialVelocity;
}
}
}
I can't really figure out why it's behaving so differently than when it's implemented within Update()... any ideas?
Sorry if that seems obvious ; I've tried looking for an answer and I couldn't find anything in recent questions.
Answer by hexagonius · Sep 13, 2015 at 08:21 PM
That's probably because you use a velocity vector calculated with Time.DeltaTime from Update. FixedUpdate uses that automatically (see the example in the Unity Script Reference for AddForce).
Thanks for the answer! I've looked at the example, but I'm not entirely sure what you mean by "does that automatically"?
your calculation:
ballVelocity = $$anonymous$$athf.Clamp(ballVelocity + (chargeRate * Time.deltaTime), 0, 800f);
needed for FixedUpdate:
ballVelocity = $$anonymous$$athf.Clamp(ballVelocity + chargeRate, 0, 800f);
Follow this Question
Related Questions
Physics after build feel different vs In-Editor (Time.deltaTime) 1 Answer
Make FixedUpdate camera be static like in Update? 0 Answers
Moving object in 'x' axis . should it be inside update or fixedupdate.? 0 Answers
Reduce framerate for server 1 Answer
Problem with DontGoThroughThings script 0 Answers