I'am working on bowling ball game and I want to detect how many bowling pins has been knocked down by ball? What is the solution for this problem?
2 Answers
Depending on precise requirements, the detection can be as simple as checking the transform.position.y
:
- (optional) add child
Top
at top of each bowling pin - When placed, record the vertical position of (
Top
of) pin each
Update()
check if pin's original and current vertical position difference is greater than a threshold (e.g. 1/2 pin height)bool isKnocked = Mathf.Abs(transform.position.y - originalY) > halfHeightThreshold;
(optional) when crossed the threshold, emit
PinKnocked
, a customUnityEvent<Pin>
which you have subscribed to in your game logic controller (e.g.GameManager
)if(isKnocked && !wasKnockedLastFrame) OnKnocked?.Invoke(this);
-
\$\begingroup\$ could you explain the 3rd step \$\endgroup\$ Commented Jun 6, 2018 at 9:39
-
\$\begingroup\$ I was using z for difference but as you guys suggested to use y axis for get the difference b/w current and original, it is working fine but still I didn't understand why and how y axis working in this problem. \$\endgroup\$ Commented Jun 6, 2018 at 10:56
-
\$\begingroup\$ @AbhinaySInghNegi it all depends on what is you
up
axis it can be either of the x,y,z or arbitrary combination of those. The default one for Unity isy
, so I guess it would make more sense to include it in the answer. \$\endgroup\$– wondraCommented Jun 6, 2018 at 15:09 -
\$\begingroup\$ hey thanks for updating your answers now it became more clear for me. \$\endgroup\$ Commented Jun 7, 2018 at 4:13
Here's an example similar to how I detected domino tipping in Last One Standing.
public class Tippable : MonoBehaviour {
// roughly 1/sqrt(2), for a 45 degree angle.
const float TIP_THRESHOLD = 0.707f;
// This lets you register another script to
// listen for "tip" events & tally them.
public UnityEvent onTip;
public bool tipped {get; private set}
// Start with a loop to check if we're tipped over.
IEnumerator Start() {
while(!tipped) {
// Wait till next frame.
yield return null;
// Check if our local up is not very upward anymore.
tipped = transform.up.y < TIP_THRESHOLD;
}
// Report that we've tipped.
onTip.Invoke();
}
}
-
\$\begingroup\$ thanks for your answers it also helped me, I have to change my code slightly. And your Last One Standing. is very nice game. \$\endgroup\$ Commented Jun 7, 2018 at 4:02