- Home /
Why does my reflect code not work?
in the attached photo is my movement and reflection code, the movement works fine, however the reflect script is not working and I cannot figure out why. I have a 2d circle with a circle collider as the "in" object, and a rectangle with a box collider as the reflector, any help is appreciated.
Can you elaborate on "not working"? What is it doing ins$$anonymous$$d?
Answer by Chimer0s · Apr 09, 2018 at 08:54 PM
It's the line "inDirection = newVelocity;" at the end. This should be "GetComponent().velocity = newVelocity;"
When you declare inDirection earlier in the code, you're actually retrieving the velocity value and storing it as a vector2. Changing the vector2 doesn't automatically change the source, it only changes that stored value.
So I tried replacing the line with GetComponent().velocity and it wanted more information so I specified that it was the rigidbody velocity that I was looking for (same way I got it for inDirection which resolved the error however the ball is still not correctly reflecting.
Have you tried debugging the value of velocity at this point, I'm not certain of the order of things but perhaps velocity has already been set to zero or another value by Unity physics? You could perhaps try using coll.relativeVelocity
ins$$anonymous$$d.
Could you explain more about what the current incorrect behaviour is.
well, when it hits the wall it kinda just rocks back and forth on the wall, I can get it to reflect if I multiply the newVelocity by more than 4, but it is a weird deflection.
What do you mean that it wanted more information? It complained until you gave used this.GetComponent<Rigidbody>()
?
CS0411 The type arguments for method 'Component.GetComponent()' cannot be inferred from the usage. Try specifying the type arguments explicitly. I get this error when I don't specify the rigidbody2d
That was a typo on my part. Sorry. It should be GetComponent().velocity as you figured.
your original post does have GetComponent().velocity = newVelocity, I don't see the typo. Good ti$$anonymous$$g btw I had someone write me a code that seemed to work for a while but it had large issues that I couldn't work around.
Your answer
Follow this Question
Related Questions
Grabpass 2D water reflection, UV issue 0 Answers
How do i make something reflect in 2D? 1 Answer
How do I get reflection vector from a 2D collision 1 Answer
2D - more lights 2 Answers