Trigger function just once after Collision #72
-
Here is my code: export default function Joueur(props) {
const { x, y, currentId, players, playersList, set, reset } = useStore()
const addScore = () => {
set(state => {state.playersList[currentId].score += 1} )
}
const [ref, api] = useBox(() => ({
type : "Dynamic",
mass :1,
args:[0.1,0.1,0.1],
...props,
onCollide: (e) => { reset(); addScore() }
}))
useFrame(()=> api.position.set(y,0.10,x));
return (
<mesh ref={ref} >
<boxBufferGeometry attach="geometry" args={[0.2,0.2,0.2]} />
<meshLambertMaterial attach="material" color={props.color} />
</mesh>
)
} I would like to find a way to trigger the function addScore juste once onCollide. |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
const { currentId, set } = useStore()
const hasCollided = useRef(false)
const addScore = () => {
hasCollided.current = true
set(state => state.playersList[currentId].score += 1)
}
const [ref] = useBox(() => ({
mass: 1,
args: [ 0.1, 0.1, 0.1 ],
onCollide: e => !hasCollided.current && addScore(),
})) Will that do the trick for you? |
Beta Was this translation helpful? Give feedback.
-
Thank you really much @codynova , it seems to work now ! |
Beta Was this translation helpful? Give feedback.
-
@Franckapik No problem, I'm happy to help. Regarding the // do something if condition is true
if (valueIsTrue) doSomething() // do something if condition is true
valueIsTrue && doSomething() |
Beta Was this translation helpful? Give feedback.
-
it couldn't be better explained! 👍 |
Beta Was this translation helpful? Give feedback.
Will that do the trick for you?