This is probably something very simple and stupid, but why doesn't it return anything? I have this simple class method:
checkCollision(event) { let eventX = event.clientX - canvasRect.left; let eventY = event.clientY - canvasRect.top; if (this.centerX - eventX <= this.radiusX && this.centerX - eventX >= (this.radiusX/-1) && this.centerY - eventY <= this.radiusY && this.centerY - eventY >= (this.radiusY/-1)) { console.log(true); return true; } else { console.log(false); return false; } }
But when running in the browser, its output is
> obj.checkCollision({clientX: 200, clientY: 200}) false <- undefined
Why doesn't it return anything? console.log is running but no return value
P粉1988143722023-09-07 10:07:18
I added some arbitrary values to the variables you used, but I was able to get your code to work like this:
const canvasRect = { left: 50, top: 50 }; const obj = { centerX: 100, centerY: 100, radiusX: 100, radiusY: 100, checkCollision(event) { let eventX = event.clientX - canvasRect.left; let eventY = event.clientY - canvasRect.top; if ( this.centerX - eventX <= this.radiusX && this.centerX - eventX >= this.radiusX / -1 && this.centerY - eventY <= this.radiusY && this.centerY - eventY >= this.radiusY / -1 ) { return true; } else { return false; } }, }; console.log(obj.checkCollision({ clientX: 200, clientY: 200 })); // >>> True
Also, a little tip. When you explicitly return true
or false
based on a Boolean expression, you can also directly return the Boolean expression itself.
const canvasRect = { left: 50, top: 50 }; const obj = { centerX: 100, centerY: 100, radiusX: 100, radiusY: 100, checkCollision(event) { let eventX = event.clientX - canvasRect.left; let eventY = event.clientY - canvasRect.top; return ( this.centerX - eventX <= this.radiusX && this.centerX - eventX >= this.radiusX / -1 && this.centerY - eventY <= this.radiusY && this.centerY - eventY >= this.radiusY / -1 ); }, }; console.log(obj.checkCollision({ clientX: 200, clientY: 200 })); // >>> True