- Home /
Simple breakout game issue
so ive been working on a simple Breakout style game. problem is, when you lose the ball below the paddle, the ball wont reset its speed to minimum. heres the script for the ball.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Ball : MonoBehaviour {
public float multiplier = 1.1f;
public float minSpeed = 5;
public float maxSpeed = 10;
public float curSpeed = 0;
private Transform _t;
public List<GameObject> blocks;
void Awake() {
_t = transform;
blocks = new List<GameObject>();
}
// Use this for initialization
void Start() {
blocks.AddRange( GameObject.FindGameObjectsWithTag( "Block" ) );
ResetBall();
}
// Update is called once per frame
void Update() {
if( blocks.Count <1 )
WonLevel();
if( _t.position.y < -5 )
MissedBall ();
}
void FixedUpdate() {
curSpeed = Vector3.Magnitude( rigidbody.velocity );
if (curSpeed > maxSpeed )
rigidbody.velocity /= curSpeed / maxSpeed;
if ( curSpeed < minSpeed && curSpeed > 0 )
rigidbody.velocity /= curSpeed / minSpeed;
}
void OnCollisionEnter( Collision col ) {
rigidbody.velocity += rigidbody.velocity * multiplier;
if( col.gameObject.CompareTag( "Block" ) )
blocks.Remove( col.gameObject );
}
private void MissedBall() {
if( Lives.curLives-- < 2 )
GameOver();
else
ResetBall();
}
private void ResetBall() {
_t.position = new Vector3( Random.Range( -Player.xBoundry + 2 , Player.xBoundry - 2), 2, Player.zPosition );
_t.LookAt( GameObject.FindGameObjectWithTag( "Player" ).transform.position );
rigidbody.AddRelativeForce( new Vector3( 0, 0, minSpeed ) );
}
private void GameOver() {
Debug.Log(" Game Over");
_t.renderer.enabled = false;
rigidbody.velocity = Vector3.zero;
_t.position = Vector3.zero;
}
private void WonLevel() {
Debug.Log( "We Won Level" );
}
}
Answer by InfiniBuzz · Jul 02, 2013 at 03:59 PM
As the name says AddRelativeForce
adds the given force to the rigidbody regardless of what force / velocity is already applied. You probably want to use
private void ResetBall() {
_t.position = new Vector3( Random.Range( -Player.xBoundry + 2 , Player.xBoundry - 2), 2, Player.zPosition );
_t.LookAt( GameObject.FindGameObjectWithTag( "Player" ).transform.position );
rigidbody.velocity = Vector3.zero; // Add this line
rigidbody.AddRelativeForce( new Vector3( 0, 0, minSpeed ) );
}
hope it solves your problem
Answer by robertbu · Jul 02, 2013 at 03:57 PM
In ResetBall() you are adding a relative force, but you are not canceling any velocity already on the ball. Try adding this at line 65:
rigidbody.velocity = Vector3.zero;
Or you can assign the velocity directly:
rigidbody.velocity = transform.foward * minSpeed;
Note that minSpeed is independent of mass, so it will need to be substantially smaller if you have the default mass of 1.0.
Your answer
Follow this Question
Related Questions
Mass affecting velocity 2 Answers
How to calculate swipe speed on iOS 2 Answers
Is unity magnitude in km/h or m/s? 1 Answer