Hi. I was fixing the boring ball problem in the method shown by Rick and Ben. But in the lecture they have take the variable myRigidBody and then accessed velocity through it. I, however, created a cached referenced Vector2 variable named myRigidBodyVelocity
and it was equal to GetComponent<Rigidbody2D>().velocity;
Then in the the method that launches the ball when mouse is clicked, instead of GetComponent<Rigidbody2D>().velocity = new Vector2(xPush,yPush);
I typed GetComponent<Rigidbody2D>().velocity = new Vector2(xPush,yPush);
But now when I clcik on the mouse the Ball breaks the connection with the paddle (as expected), but it isnt launched (i.e. its celocity doesnt change). I would be very happy to understand the reason of this bug.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ball : MonoBehaviour
{
[SerializeField] Paddle paddle1;
[SerializeField] float xPush = 2f;
[SerializeField] float yPush = 15f;
[SerializeField] AudioClip[] ballSounds;
[SerializeField] float randomFactor = 0.2f;
Vector2 paddleToBall;
bool hasStarted;
Vector2 myRigidBodyVelocity ;
void Start()
{
paddleToBall = transform.position - paddle1.transform.position;
hasStarted = false;
myRigidBodyVelocity = GetComponent<Rigidbody2D>().velocity;
}
// Update is called once per frame
void Update()
{
if(hasStarted == false)
{
LockBallToPaddle();
}
LaunchBallOnClick();
}
private void LaunchBallOnClick()
{
if(Input.GetMouseButtonDown(0))
{
myRigidBodyVelocity = new Vector2(xPush,yPush);
hasStarted = true;
}
}
private void LockBallToPaddle()
{
Vector2 paddlePos = new Vector2(paddle1.transform.position.x, paddle1.transform.position.y);
transform.position = paddlePos + paddleToBall;
}
/*private void OnCollisionEnter2D(Collision2D collision)
{
if(hasStarted == true)
{
AudioClip clip = ballSounds[UnityEngine.Random.Range(0,ballSounds.Length)];
GetComponent<AudioSource>().PlayOneShot(clip);
}
}*/
}