When the mouse is clicked, the character fails to reach the intended destination or moves in the wrong direction on the HTML canvas

UPDATE: RESOLVED

I am currently working on a game where the character moves by right-clicking. The character is meant to walk slowly, not teleport, towards the destination set by right-clicking on the canvas. However, I have encountered an issue where the character is moving towards a different position than intended despite my efforts to calculate the correct angle and debug using a circle drawing function. As a novice in this field, I find it challenging to comprehend the math involved and its impact on the character's movement.

The problem can be visualized through this reference image: https://i.stack.imgur.com/SBNK6.jpg

Additionally, my goal is illustrated in this image: https://i.stack.imgur.com/hdkiJ.jpg

        //VARIABLES_________________________________
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        var WIDTH = 640;
        var HEIGHT = 360;
        var CANVAS_WIDTH = 640;
        var CANVAS_HEIGHT = 360;
        var renderList = [];

        var selfX = 250;
        var selfY = 100
        var frameX = 0;
        var playerSpdX = 0;
        var playerSpdY = 0;
        var drawDest = false;
        var destX;
        var destY;

        var Img = {};
        Img.player = new Image();
        Img.player.src = "Human_walk_spritesheet.png";
        Img.map = new Image();
        Img.map.src = "maptest.png";
        Img.bullet = new Image();
        Img.bullet.src = "bullet.png";


        renderList.push({img: Img.player, spdX: playerSpdX, spdY: playerSpdY, currX: selfX, currY: selfY});

        //CODE______________________________________
        function render(){
            ctx.clearRect(0,0, CANVAS_WIDTH, CANVAS_HEIGHT);

            ctx.drawImage(Img.map, 0, 0);

            for(i in renderList){
                var renderObject = renderList[i];


                renderObject.currX += playerSpdX;
                renderObject.currY += playerSpdY;

                selfX = renderObject.currX;
                selfY = renderObject.currY;

                ctx.drawImage(renderObject.img, frameX, 0, 120, 218, selfX, selfY, renderObject.img.width/31/8, renderObject.img.height/8);
            }
            if(drawDest)
            ctx.drawImage(Img.bullet, destX, destY);

            updateAnimation();
        }

        setInterval(render, 100);


        document.onmousedown = function click(event){
            if(event.button == 2){//right click
                clickX = event.clientX;
                clickY = event.clientY;

                clickX -= selfX;
                clickY -= selfY;

                aimAngle = Math.atan2(clickY, clickX) / Math.PI * 180;
                var spdX = Math.cos(aimAngle/180*Math.PI)*10;
                var spdY = Math.sin(aimAngle/180*Math.PI)*10;
                setPlayerSpeed(spdX, spdY);
                drawDestinationDot(clickX, clickY);
            }
        }



        document.oncontextmenu = function(mouse){
            mouse.preventDefault();
        }


        function setPlayerSpeed(spdX, spdY){
            playerSpdX = spdX;
            playerSpdY = spdY;
        }

        function drawDestinationDot(x, y){
            drawDest = true;
            destX = x;
            destY = y;
        }

Answer №1

After dedicating over 72 hours to solving the issue both before and after my initial post, I finally identified the root cause of the problem. Admittedly, I take partial blame for not including all the code initially. Following Stack Overflow guidelines, I aimed to provide only the necessary code to avoid confusion among potential helpers. However, I overlooked a crucial part that I deemed irrelevant at first. Being relatively new to this field, I failed to consider the impact of canvas resizing. When I simplified my code by using basic rectangles instead of images, everything worked flawlessly. The missing piece was the canvas resizing function:

resizeCanvas();
        function resizeCanvas(){
            CANVAS_WIDTH = window.innerWidth - 4;
            CANVAS_HEIGHT = window.innerHeight - 4;

            let ratio = 16 / 9;
            if(CANVAS_HEIGHT < CANVAS_WIDTH / ratio)
                CANVAS_WIDTH = CANVAS_HEIGHT * ratio;
            else
                CANVAS_HEIGHT = CANVAS_WIDTH / ratio;

            canvas.width = WIDTH;
            canvas.height = HEIGHT;

            canvas.style.width = '' + CANVAS_WIDTH + 'px';
            canvas.style.height = '' + CANVAS_HEIGHT + 'px';
        }

A big thank you goes out to Loïc for assisting me in resolving this issue.

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

Can you provide a database of words for different cities, towns, and countries in MongoDB (or in JSON

Currently, I am in the process of developing an application that utilizes MongoDB. One specific feature I am working on implementing is an 'auto-suggest' functionality on the front-end. For example, as a user begins to type the first few letters ...

Issue: Encounter of "Uncaught (in promise) TypeError" while implementing RiveScript chatbot in Angular

I've been working on integrating a chatbot based on RiveScript into Angular. The chatbot is functioning well - I always see the correct response in the console. Displaying the user's input is also working seamlessly. However, I'm encounterin ...

Iterating over a table and selecting a specific button on the rows that meet a specific condition

I'm having a bit of trouble and would really appreciate your help. I'm attempting to write a script that will scan through this table and delete any row that contains the word "active". The script needs to check every row in the table. The code ...

Inject nested controller dynamically

I am working on a straightforward ASP.NET MVC application that includes an ng-controller. I am trying to inject another ng-controller inside this controller using a partial view, but I'm having trouble getting the binding to work correctly. You can s ...

How to use the Enter key to submit a form in react.js with the help of "@material-ui/core/Button"

Here is the form I have created using the render method for user sign-in. <form onSubmit={this.handleSubmit}> <Avatar className={classes.avatar}> <LockOutlinedIcon /> </Avatar> <Typography component="h1" varia ...

Can you explain the distinction between ng-init and ng-bind?

Here is a code snippet utilizing ng-init: <!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <body> <div ng-app="" ng-init="names=['Jani','Heg ...

React infinite scroller - component fails to work when initial items are insufficiently loaded

In my Next.js app, I am dealing with a large firestore database containing many book objects. To filter these books based on keywords in their title, category, author, etc., I have implemented a searchbar. Due to the sheer volume of books, I am utilizing l ...

What are the differences in how a link tag responds on mobile devices?

I have a question regarding opening a pdf in an iframe on the current page. Is there a way to handle this differently for mobile/tablet users? For example, clicking the link could open it in another tab for better readability instead of within the iframe ...

Delivering Background Videos with Node.JS

Apologies if my question seems off base or confusing, as I am not very knowledgeable in the world of nodejs. I have been comfortable using just plain PHP and Apache for a while until I discovered ZURB Foundation's stack with Handlebars and SASS, along ...

What is the best way to incorporate jQuery's default handsontable into an AngularJS directive?

I currently have a handsontable functioning in a non-AngularJS application, and I am in the process of developing a new version of the software that heavily utilizes AngularJS (SPA). My question is: is it possible to encapsulate the existing handsontable ...

Run the command "node index.js" to simultaneously start and stop the server

After installing WSL2 and the Ubuntu 22.04 distribution on Windows 11, I set up my environment, installed nvm, Node version 16.17.1, and then ran npm init in my folder. Following that, I installed Express and created an index.js file with a simple structur ...

Forwarding the geographic coordinates directly to the system's database

I have a unique script that retrieves the precise latitude and longitude position. It then automatically sends this data to a database without the need for user input. <script> function getPosition(position) { var latitude = position.coor ...

Arrange the header and input within a div using flexbox to achieve different alignments

I need help aligning the header section vertically and ensuring responsiveness. Using margin-top isn't fully responsive, so I want to align the header at the beginning of the input field. { margin: 0px; padding: 0px; color: white; } #h ...

When you hover over a dropdown menu, the content underneath it is raised slightly and a margin is formed on the right side of the page

I am facing some technical difficulties with my photography website, specifically on the "Contact" and "Bio" pages. The issue arises when the screen is resized, causing layout changes. When hovering over the "Albums" menu tab and the drop-down menu appears ...

Creating a script to open multiple URLs in HTML and JavaScript

Currently, I am working on creating a multiple URL opener using HTML and JavaScript. However, I have encountered an issue where HTTP links are opening fine but HTTPS links are not. Can someone provide assistance with this problem? Below is the code snippet ...

CSS vertical alignment: Getting it just right

I am currently using Bootstrap and below is a snippet of the code I have implemented. <div class="row"> <div class="col-lg-6"><img src="#" alt=""></div> <div class="col-lg-6"> <h2>Heading</h2> ...

What is the process for animating classes instead of ids in CSS?

My webpage currently features a setup similar to this. function wiggle(){ var parent = document.getElementById("wiggle"); var string = parent.innerHTML; parent.innerHTML = ""; string.split(""); var i = 0, length = string.length; for (i; i ...

What are the steps to leverage npm installed packages in my .js files?

I'm new to web development and I'm trying to incorporate node packages into my workflow. Specifically, I'm attempting to test out the axios ajax library. It seemed like this would be a simple task, but it's proving to be quite challeng ...

The autoplay feature for YouTube videos is not functioning on Chrome when viewed on an iPhone

if($('.explore-video-btn').length > 0) { var video_id = youtube_parser($('.explore-video-btn').attr('data-video-url')); } var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api" ...

When the text exceeds its container, the CSS property overflow will display only the

.example{ overflow:auto; } <div class="example"> <p>Some Additional Text Here<P> </div> This particular code snippet showcases the initial portion of the text, allowing for scrolling down to reveal items 5 and 6: 1 2 ...