- Home /
Question by
Yellowyogurts · Oct 20, 2016 at 07:56 PM ·
velocitybounceflippingy
How come my the y velocity does not change in the script.
The problem is as you can see below is that when the ball touches a wall it does not bounce as i want it. https://gfycat.com/ShadyPortlyBug
This is the script for bouncing.
void OnCollisionEnter2D(Collision2D coll)
{
Debug.Log(GetComponent<Rigidbody2D>().velocity.y);
var newPS = Instantiate(ballhit, transform.position, transform.rotation) as ParticleSystem;
newPS.startColor = coll.gameObject.GetComponent<SpriteRenderer>().color * GetComponent<SpriteRenderer>().color * 0.5f;
if (coll.gameObject.tag == "Walls")
{
var rb2d = GetComponent<Rigidbody2D>();
rb2d.velocity = new Vector2(rb2d.velocity.x , rb2d.velocity.y * -1);
}
if (coll.gameObject.tag == "Paddle" && directionRight == currentDirection)
{
LeftDir();
}
else if (coll.gameObject.tag == "Paddle" && directionLeft == currentDirection)
{
RightDir();
}
//BallsMovement based on the paddles y position.
if (coll.gameObject.name == "LeftPaddle")
{
GetComponent<SpriteRenderer>().color = coll.gameObject.GetComponent<SpriteRenderer>().color;
float y = hitFactor(transform.position,
coll.transform.position,
coll.collider.bounds.size.y);
// Calculate direction, make length=1 via .normalized
Vector2 dir = new Vector2(1, y).normalized;
// Set Velocity with dir * speed
GetComponent<Rigidbody2D>().velocity = dir * speed;
}
if (coll.gameObject.name == "RightPaddle")
{
GetComponent<SpriteRenderer>().color = coll.gameObject.GetComponent<SpriteRenderer>().color;
// Calculate hit Factor
float y = hitFactor(transform.position,
coll.transform.position,
coll.collider.bounds.size.y);
// Calculate direction, make length=1 via .normalized
Vector2 dir = new Vector2(-1, y).normalized;
// Set Velocity with dir * speed
GetComponent<Rigidbody2D>().velocity = dir * speed;
}
}
I would really appreciate a tip or explanation
Comment
Answer by Yellowyogurts · Oct 21, 2016 at 11:47 PM
Well it is as the hero said. Just had to switch to relativevelocity instead of normal rb2d.velocity.y = coll.relativeVelocity.y
Your answer
Follow this Question
Related Questions
Moving a ball in the opposite direction of where it hits 1 Answer
Multiply by a magnitude 1 Answer
hinge joint bounce min velocity - physical explanation please 0 Answers
How do I get velocity from a collision? 1 Answer
Bouncing Ball Game 3 Answers