What i want to do is to detect each side when my character(ThirdPerSonController) touch a cube. In fact my main goal is to detect when my player is standing on the cube surface on top. This is my script:
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
void OnCollisionEnter(Collision collision)
{
ContactPoint contact = collision.contacts[0];
Vector3 normal = contact.normal;
Vector3 inverseNormal = transform.InverseTransformDirection(normal);
Vector3 roundNormal = RoundVector3(inverseNormal);
ReturnSide(roundNormal);
}
Vector3 RoundVector3(Vector3 convertThis)
{
int x = (int)Mathf.Round(convertThis.x);
int y = (int)Mathf.Round(convertThis.y);
int z = (int)Mathf.Round(convertThis.z);
Vector3 returnVector = new Vector3(x, y, z);
return returnVector;
}
void ReturnSide(Vector3 side)
{
string output = null;
switch (side)
{
case Vector3.down:
output = "Down";
break;
case Vector3.up:
output = "Up";
break;
case Vector3.back:
output = "Back";
break;
case Vector3.forward:
output = "Front";
break;
case Vector3.left:
output = "Left";
break;
case Vector3.right:
output = "Right";
break;
}
Debug.Log(output + " was hit.");
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
I'm getting error on the line:
switch (side)
Severity Code Description Project File Line Suppression State Error CS0151 A switch expression or case label must be a bool, char, string, integral, enum, or corresponding nullable type test.cs 33 Active
With C# 7, you can do this. You case use the when
statement:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch#the-case-statement-and-the-when-clause
So, for example, if you wanted to know which side of a cube is clicked, you can use something like this:
void OnMouseDown()
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, Mathf.Infinity))
{
switch (hit.normal)
{
case Vector3 v when v.Equals(Vector3.up):
Debug.Log("Up");
break;
case Vector3 v when v.Equals(Vector3.left):
Debug.Log("Left");
break;
case Vector3 v when v.Equals(Vector3.back):
Debug.Log("Back");
break;
}
}
}
I'm not sure about the efficiency of this method. YMMV.
No, there is no way to make a switch/case using Vector3.
"A switch expression or case label must be a bool, char, string, integral, enum or corresponding nullable type."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With