Player-Oriented Online Game: Addressing Target Accuracy Challenges in ctx.setTransform

I'm currently developing a web game and my goal is to ensure that the player remains at the center of the screen. However, as the player moves further away from the center, the accuracy decreases. I've attempted using ctx.setTransform, which works well for movement but causes issues with aiming. To highlight this problem, I added a red dot indicating where the player is aiming.

var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvasWidth = canvas.width;
canvasHeight = canvas.height;

// The rest of the JavaScript code...

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas></canvas>
    <script src="minscript.js"></script>
</body>
</html>

Answer №1

It appears that the current selection in the canvas is not reflecting the actual mouse position.

To address this issue, check out the following post Real mouse position in canvas

This script now considers the canvas in relation to the window:

document.addEventListener("mousemove", function (e) {
  var bound = canvas.getBoundingClientRect();
  lastMouseX = event.clientX - bound.left - canvas.clientLeft;
  lastMouseY = event.clientY - bound.top - canvas.clientTop;
});

var canvas = document.querySelector("canvas");
var ctx = canvas.getContext("2d");

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
canvasWidth = canvas.width;
canvasHeight = canvas.height;

// Additional code for Player class and Bullet class...
// ...
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas></canvas>
    <script src="minscript.js"></script>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on accessing the first element in an array when performing multiplication within the Interval component in React.js

I am having trouble initiating an if statement from number 0 once the window is loaded, as it seems to be skipping over 0 and starting from 1 instead. Can someone please assist me in understanding how this works? showAnime = () => { let counter ...

Bootstrap 4 tabs function perfectly in pairs, but encounter issues when there are three of them

Having trouble with bootstrap4 tabs not working properly? They function well with 2 tabs using the code below: <div class="row"> <div class="col-12"> <ul class="nav nav-tabs" id="registration-picker-acc-select" role="tablist"> ...

Creating interactive <td> elements in HTML with JavaScript editor capabilities

Currently, I am working on creating an editable table feature and managed to find a good example to follow. However, I have encountered some issues along the way. <td contenteditable="true" class="hover" onBlur="saveToDatabase(this,'question' ...

Methods for eliminating curly braces from HTTP response in JavaScript before displaying them on a webpage

When utilizing JavaScript to display an HTTP response on the page, it currently shows the message with curly braces like this: {"Result":"SUCCESS"} Is there a way to render the response message on the page without including the curly braces? This is the ...

Incorporating Bootstrap Navbar into a create-react-app project

I recently created a new project using create-react-app. To incorporate Bootstrap into my project, I followed these steps: npm install --save bootstrap@3 Next, I imported Bootstrap in my root file index.js: import 'bootstrap/dist/css/bootstrap.css& ...

Exploring the Power of React's Ref API

Currently, I am following tutorials on Udemy by Max where he discusses how to work with Ref Api's in React 16.3. In one of the lectures, he demonstrated creating a ref inside a container class, not App.js, using this.lastref = React.createRef();. He ...

Guide on incorporating an Angular directive to substitute an element under specific conditions

My goal is to create a directive that replaces an anchor element with a div element under certain conditions. The content of the anchor element should remain unchanged and be included within the new element. The concept involves having an attribute on the ...

What is the best way to enable a child category on a treeview within a Vue component?

I am working with two vue components. The first component (parent component) looks like this: <template> ... <ul class="filter-category" v-for="list in categories"> <list-category :data="list" :category-id="category ...

Arranging numerous Text elements within a solitary Drag and Drop container with the z-index property

I am facing a challenge with stacking twelve arguments in no particular order on a drag and drop element. The texts overlap each other, making it difficult for the end user to see them clearly when dragging and dropping. Is there a way to stack texts using ...

Get the image resolution at the same time

I need a function that can take a URL pointing to an image as a parameter and synchronously provide the resolution of that image. The function should pause execution until the image is fully retrieved. Here is an example of what I'm looking for: func ...

Are React.Fragment and DocumentFragment interchangeable in React?

React.Fragment resembles DocumentFragment. But does React.Fragment offer the same performance advantages as DocumentFragment? Put differently, do these two code snippets: // index.jsx const arr = [...Array.from({length: 10000})]; return ( <ul> ...

Limit the Jquery selection specifically to elements on the modal page

Recently I encountered an issue with a webpage that opens a modal form. The problem arises when the validation function, written in JQuery, checks all fields on both the modal and the page beneath it. //validate function function validateFields() { v ...

The JavaScript confirm function will provide a false return value

Is it necessary to display a confirmation message asking "Are you sure ..."? I have implemented the message, but the function return false; is not working when the user clicks NO. <script> function confirmDelete(){ var answer = confirm("Are you su ...

Tips for maintaining the current route in Vue.js after a page refresh while running the Vue.js project in development mode on a specific port?

In my router.ts file, I have defined two routes: export default new Router({ mode: "history", routes: [ { path: "/", component: require("./components/dashboard/Dashboard.vue")}, { path: "/counter", component: require("./components/ ...

The Radio button and Checkbox values are causing an issue where the Radio button is continuously summing upon clicking without a limit. Why is this happening? Check out

I'm currently stuck in a function and believe it would be helpful for you to guide me along the correct path. My goal is to sum the values of checked boxes with the values of checked radio buttons. However, the radio values are continuously accumulat ...

Is Highcharts-angular (Highcharts wrapper for Angular) compatible with Angular 4?

I have attempted to install various versions of highcharts-angular, ranging from 2.0.0 to 2.10.0. However, I consistently encounter the same error when running the application. The error message states: Metadata version mismatch for module C:/dev/Angular- ...

What is the best way to import my json information into an HTML table and customize the rows as radio buttons using only Javascript?

I am facing an issue with processing a JSON response: var jsondata = dojo.fromJson(response); There is also a string that I am working with: var jsonString = jsondata.items; The variable jsonString represents the JSON data in the file: jsonString="[ ...

What might be the reason for jQuery not functioning in Internet Explorer 11?

Working on developing a slideout menu for my website using jQuery. It functions perfectly in Chrome, but encountering issues in Internet Explorer (IE11). Extensive search hasn't provided a solution yet. Seeking assistance and any help would be highly ...

The jQuery click event does not fire within a bootstrap carousel

I am trying to set up a bootstrap carousel where clicking on an image inside it will trigger a self-made lightbox. However, I am facing some issues with the JavaScript code not being triggered with the following syntax: $('html').on("click", ".l ...

Executing script once the DOM has completed loading

In my project, I'm dynamically generating menu items for a menu bar based on headers from external files that are imported using an XMLHttpRequest(). The menu bar is then updated as I navigate through different pages. Everything works smoothly. Each ...