- Home /
How can I detect for 2 different component types using an interface on RayCast Hit?
I have a game where you swipe to hit balls, (basically). The game will also have power ups which the player can tap on. When the user swipes and hits a ball, a force is calculated and sent the the ball. However, the power ups do not need a force applied, only need to be told they are hit. I am new to interfaces and probably not doing it right, but I am trying to have one interface where both the balls and power ups can inherit from. It will have a "OnHit" function which is called on the raycast script. If it is a ball, I will need to send a force to the OnHit(), but if its a powerup, I dont need any parameters.
private void CastRay (int i)
{
Ray raycast = Camera.main.ScreenPointToRay (Input.touches [i].position);
RaycastHit rayHit;
ISwipeable swipe;
if (Physics.Raycast (raycast , out rayHit) && ((swipe = rayHit.collider.GetComponent<ISwipeable> ()) != null))
{
Vector2 direction = rayHit.collider.transform.position - rayHit.point;
float accel = Input.GetTouch (i).deltaPosition.magnitude / Input.GetTouch (i).deltaTime;
Vector2 force = direction * accel;
swipe.OnSwipe (force);
touchHit [i] = true;
}
}
Basically I am looking for the most efficient and proper way to check if the raycasthit collider has a "hittable" component, and to check weather I should send a force to it if it is.
Answer by fafase · Nov 20, 2019 at 07:11 AM
It's all about how the interface is implemented. The consumer class (the one using the interface object) should not care about or know what is done in the interface, so it would call it and that's it. Then in the implementation it either uses or not the parameter.
Now if you want to prevent some computation because the force is not needed, you can extend your interface:
public interface ISwipeable
{
void OnSwipe (float force);
void OnHit();
bool UseForce{ get; }
}
public class Ball: MonoBehaviour, ISwipeable
{
public bool UseForce{ get { return false; } }
}
public class PowerUp: MonoBehaviour, ISwipeable
{
public bool UseForce{ get { return true; } }
}
if (Physics.Raycast (raycast , out rayHit) && ((swipe = rayHit.collider.GetComponent<ISwipeable> ()) != null))
{
if(swipe.UseForce)
{
Vector2 direction = rayHit.collider.transform.position - rayHit.point;
float accel = Input.GetTouch (i).deltaPosition.magnitude / Input.GetTouch (i).deltaTime;
Vector2 force = direction * accel;
swipe.OnSwipe (force);
}
else
{ swipe.OnHit(); }
touchHit [i] = true;
}
Awsome! Thanks alot, I was trying to put a boolean in the interface but it wasn't working. I didnt realize you need a getter ins$$anonymous$$d.