Error CS0201 when trying to change RigidbodyConstraints
Hello there! My game has a ball that rolls when you use the arrow keys, however I want it to stop rolling once you release the arrows keys so it doesn't roll of the edge.
I'm using Rigidbody.Constraints to constrain the X and Z axys so it stops rolling, but it will still fall to it's doom when it is rolled over the edge.
I'm using the following code, but it's giving me an error CS0201 for the 4th, 8th and 9th line.
if (movement != Vector3.zero) {
rb.AddForce (movement * speed);
if (RigidbodyConstraints.FreezePositionX && RigidbodyConstraints.FreezePositionZ) {
RigidbodyConstraints.None;
}
} else {
if (RigidbodyConstraints.None) {
RigidbodyConstraints.FreezePositionX;
RigidbodyConstraints.FreezePositionZ;
}
}
What am I doing wrong here and how could I improve my code?
Answer by Landern · Nov 11, 2016 at 02:22 PM
It's because you're not assigning anything, you're just calling various enumerations of type RigidbodyConstraints. What you're looking for i would assume is to Change the rb(Your rigidbody) constraints. To add addition context, if i was driving down the road and just said "HOTDOG!" it's possible the other people in the car would have an exception to this statement since it would make no sense; did i want a hotdog? did i see a got dog? However if i would say, "That car looks like a hotdog" then the other people would think i've set a attribute/characteristic of a hotdog. Kinda the same thing here(i stress kind of), but just saying RigidbodyConstraints.None(or any other options of the enum) doesn't affect anything or using an if statement with the enum isn't doing anything, it's not comparing something to something, its just like saying Hotdog out of the blue.
I would adjust your code to compare(assuming i'm correct) the rb.constraints variable, you will need to use bitwise operations(sorry, this topic can get confusing for the uninitiated) to compare combined bit values of the enum of type RigidbodyConstraints.
The change:
if (movement != Vector3.zero) {
rb.AddForce (movement * speed);
if ((rb.constraints & RigidbodyConstraints.FreezePositionX & RigidbodyConstraints.FreezePositionZ) == RigidbodyConstraints.FreezePositionX & RigidbodyConstraints.FreezePositionZ) {
rb.constraints = RigidbodyConstraints.None;
}
} else {
if (rb.constraints = RigidbodyConstraints.None) {
rb.constraints = RigidbodyConstraints.FreezePositionX | RigidbodyConstraints.FreezePositionZ;
}
}
In .net 4.0 this can be further simplified by using the Enum.HasFlags method which checks for flags, this will make things easier to read.
Your answer
Follow this Question
Related Questions
Jump is higher then normal 0 Answers
How to make Rigidbody movement not slippery? 4 Answers
Stopping Moving Objects? 0 Answers