So some teammates and I have to come up with a way for the player to have different abilities based on what color block they are standing on. The player already has the ability to change a blocks color, but we need to have different abilities attached to those specific colors.
For example, if they are standing on a block they colored blue, they will have the ability to jump higher, red they will be heavier, and green they will be faster.
The ability needs to go away when not touching that color too.
The way I would do it, is to add an enum which would hold the colors that you already have decided on.
enum Colors {NoColor, Blue, Red, Green};
Colors currentColor = Colors.NoColor;
Then, each player could do a raycast down, that would return the color of the block they are standing on, and then update the enum to the color that was returned.
In turn, you’d have a method that would be called, which would change up the variables for jumpHeight, speed or weight.
Personally, I’d use a switch, but you can figure out another way to do so.
switch (currentColor){
// you could send in the variables in UpdateVariables method - implement it the way you want.
case Colors.Red:
UpdateVariables(--variables--);
break;
case Colors.Green:
UpdateVariables(--variables--);
break;
case Colors.Blue:
UpdateVariables(--variables--);
break;
}
One solution would be to make prefabs from those blocks, and attach a script to them, which has an integer variable in it. This variable (lets name it ‘blockType’) will identify the power-up of the block. You could also create a public ‘ChangeBlock’ method in it, and when you want to change the cube, you should call this method with passing the variables you need.
The player object should have a script too. In this script, you can check the block underneath with casting a ray.
RaycastHit hit;
Physics.Raycast(transform.position, -transform.up, out hit);
This function will cast a ray downwards starting from the player transform. It fills the ‘hit’ instance with data about the first collider it hits. Then you could get the component, and check the block type. After that, it is your job to implement the changes.
RaycastHit hit;
if(Physics.Raycast(transform.position, -transform.up, out hit))
{
int blockType = hit.transform.GetComponent<BlockScript>().blockType;
}
Note that if it hits anything else, which has no BlockScript on it, it will throw an error. You may want to create a new layer mask and apply it to the raycasting function. You can find a lot of tutorials about layers.
After this function, you should create an ApplyAbility() function to change the abilities. The function should get the blockType variable as a parameter, and apply changes on the PlayerScript to make it jump higher and so on.