I'm creating a game with JavaScript and HTML Canvas. It's a multiplayer 2D game with tanks that try to hit each other. The tanks can move as well as rotate. How can you figure out collision detection with rotating rectangular objects? I know, I could make them square and use circular detection, but it looks very messy when a tank runs into a wall. Thanks for all who try to help :)
HTML Canvas and JavaScript rotating objects with collision detection
2.2k Views Asked by Sam D. At
1
There are 1 best solutions below
Related Questions in JAVASCRIPT
- Using Puppeteer to scrape a public API only when the data changes
- inline SVG text (js)
- An array of images and a for loop display the buttons. How to assign each button to open its own block by name?
- Storing the preferred font-size in localStorage
- Simple movie API request not showing up in the console log
- Authenticate Flask rest API
- Deploying sveltekit app with gunjs on vercel throws cannot find module './lib/text-encoding'
- How to request administrator rights?
- mp4 embedded videos within github pages website not loading
- Scrimba tutorial was working, suddenly stopped even trying the default
- In Datatables, start value resets to 0, when column sorting
- How do I link two models in mongoose?
- parameter values only being sent to certain columns in google sheet?
- Run main several times of wasm in browser
- Variable inside a Variable, not updating
Related Questions in HTML
- How to store a date/time in sqlite (or something similar to a date)
- How to use custom font during html to pdf conversion?
- Storing the preferred font-size in localStorage
- mp4 embedded videos within github pages website not loading
- Scrimba tutorial was working, suddenly stopped even trying the default
- Is there any way to glow this bulb image like a real light bulb
- With non-graphical maps in Leaflet, zoomDelta doesn't work
- What can I do to improve my coding on both html and css
- Uncaught TypeError: google.maps.LatLng is not a constructor at init (script.js:7:13)
- Bootstrap modal not showing at the desired position on a web page when the screen size is smaller
- Displaying a Movie List on a Website Using Jinja2 and Bootstrap
- How to redirect to thank you page after submitting a Google form embedded into a Google Site?
- Storing selected language in localStorage
- Fences (parenthesis, braces) in HTML and MathML
- Understanding Scroll Anchoring Behavoir
Related Questions in CANVAS
- Random number generator in Python Canvas
- When I use electron js and canvas in node js, I get a rebuild module error
- How to set an individual mouse scroll on two different canvases that are connected to separate frames but the frames are one on top of eachother?
- Positioning for sliders and canvas
- How to perfectly align textarea and canvas fillText
- Rust Ownership Challenges in Drawing Application: Need Assistance with Code Section
- Zoom In/Out particular Object with Touch in Fabric JS
- How to send a big array to a client faster
- Android: How to scale a bitmap to fit the screen size using canvas?
- How can i resize canva and send resized data to database?
- Given a convex polygon as a set of edges how to fill the area inside depending on the distance to the closest edge
- SigmaJS: Create a snapshot of "sigma-containter"
- Draw local image on canvas using react-native-canvas
- Rotating multiple objects around the origin (JavaScript Canvas)
- How to proper rotate object with a 45-degree angle using OrbitControls?
Related Questions in COLLISION
- Brick Breaker Ball Bounce
- I am trying to make a Turtle Eater Game and I'm running into a minor bug(kind of)
- Points system in Unity not working. I want to count points but make both objects disappear and it's not working
- How to make wall collision with staticbody2d & collisionshape2d ( using an area2D for player with collisionshape2d as a child ) in GODOT?
- How do you get the numerical values in this collision function
- Pygame slows down after Collision Handling PacMan
- Problem with a wall collision on a map loaded from a png file (like the raylib maze example)
- How to make collisions with rects in pygame
- pygame collisions while character is on a tile
- onCollisionEnter is not working in r3f how can i fix it?
- How to handle collision after a diagonal movement with rectangles
- Inverting a hitbox
- Gamemaker collisions
- Python Pygame Platformer
- Java Ball Movement: Unexpected Behavior with Boundary Reflections
Related Questions in DETECTION
- AttributeError: 'Results' object has no attribute 'box'. can anyone explain this?
- How to calculate the two-dimensional centroid coordinates calculated from the human joints using Openpose
- Yolo makes one box for intersecting objects
- Flutter: How to detect platform-level edge swipes?
- Word-Addin heading detection
- Implementing Device-Specific Redirects in Angular Routing
- Plot probability of detection against number of surveys using 'unmarked' package
- The best methods to report object mesh problems?
- I have get error in jupyter noteboook Kernel Restarting The kernel for opencv_faces.ipynb appears to have died. It will restart automatically
- Barcode detection from an image on server side (particularly on node.js)
- Opencv movement detection without being trigger by random noise
- Java Garbage Cleaner detector
- Can a detection be written from Github audit events that finds commit/pushes done after review approvals in pull requests?
- How to split in R
- Get the Coordinate of Original Image
Trending Questions
- UIImageView Frame Doesn't Reflect Constraints
- Is it possible to use adb commands to click on a view by finding its ID?
- How to create a new web character symbol recognizable by html/javascript?
- Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
- Heap Gives Page Fault
- Connect ffmpeg to Visual Studio 2008
- Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
- How to avoid default initialization of objects in std::vector?
- second argument of the command line arguments in a format other than char** argv or char* argv[]
- How to improve efficiency of algorithm which generates next lexicographic permutation?
- Navigating to the another actvity app getting crash in android
- How to read the particular message format in android and store in sqlite database?
- Resetting inventory status after order is cancelled
- Efficiently compute powers of X in SSE/AVX
- Insert into an external database using ajax and php : POST 500 (Internal Server Error)
Popular # Hahtags
Popular Questions
- How do I undo the most recent local commits in Git?
- How can I remove a specific item from an array in JavaScript?
- How do I delete a Git branch locally and remotely?
- Find all files containing a specific text (string) on Linux?
- How do I revert a Git repository to a previous commit?
- How do I create an HTML button that acts like a link?
- How do I check out a remote Git branch?
- How do I force "git pull" to overwrite local files?
- How do I list all files of a directory?
- How to check whether a string contains a substring in JavaScript?
- How do I redirect to another webpage?
- How can I iterate over rows in a Pandas DataFrame?
- How do I convert a String to an int in Java?
- Does Python have a string 'contains' substring method?
- How do I check if a string contains a specific word?
Move hit point to local space
First an alternative
There are many ways you can do it. The simplest way. When you calculate the cross product between a point and a line it will be negative if the point is right of the line and positive if left. If you then do each of the four sides in turn and they are all the same sign the point must be inside.
To get the cross product of a line and a point
A Quicker way.
But that is a lot of math for each object and each bullet.
The best way is to transform the bullet into the tanks local coordinate system then its just a simple matter of testing the bounds, left, right, top, bottom.
To do that you need to invert the tanks transformation matrix. Unfortunately the easy way to do that is currently still behind browser flags/prefixes so you need to create and manipulate the transformations in javascript. (Should not be too long till ctx.getTransform() is implemented across the board and fill a very needed performance hole in the canvas 2d API)
If ctx.getTransform is available
So you have a tank at x,y and rotated r and you draw it with
The transform hold everything we need to do the calcs, all we need to do is invert it and then multiply the bullet with the inverted matrix
The bullet is at bx,by so create a DOMPoint
Then for each tank transform the bullet with DOMMatrix.transformPoint
Now just do the test in the tanks local coord space
The Javascript way
Well until the becomes the norm you have to do it the long way. Using the same x,y,r for tank, bx,by for bullet.
Test to make sure it works
Too many negatives, xdx,xdy etc etc for me to be able to see if I got it correct (Turned out I put the wrong sign in the determinant) so here is a quick demo to show it in action and working.
Use the mouse to move over the tank body and it will show that it is hit in red. You could extend it easily to also hit the tank moving parts. You just need the inverse transform of the turret to get the bullet in local space to do the test.
UPDATE
Add code to stop tank's visually popping in and out as the crossed canvas edge. This is done by subtracting an
OFFSETfrom each tank when displayed. This offset must be factored in when doing the hit test by addingOFFSETto the test coordinates.