Can an image be coded to follow the cursor once it reaches the image itself?

I'm in the process of developing a game where an image follows the cursor. I want to prevent players from cheating by moving the cursor outside the designated area and then reaching the finish line. Currently, the image moves wherever my cursor goes. Any suggestions on how to address this?

Here is the code snippet:

  

$(document).mousemove(function(e){
    $("#image").css({left:e.pageX, top:e.pageY});
});
    
    * {cursor: none;}
#image{
position:absolute;
width:25px;
height:auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>      
    <img id="image" src="http://static.micheljansen.org/uploads/mac-osx-arrow-cursor.png"/>

Check out the JsFiddle demo here: https://jsfiddle.net/3x7cgLdr/

Answer №1

Perhaps this solution may be what you're looking for and could offer some assistance.

In the code snippet below, I have defined a variable var startMove which starts as false when the cursor moves away from the document. It will only change to true when the mouse comes within 50 units of the image, triggering the movement of the image. For a live example, refer to: https://jsfiddle.net/IA7medd/3x7cgLdr/2/

var startMove;
$(document).mousemove(function(e){
    var difLeft = $('#image').offset().left - e.pageX;
    var difTop = $('#image').offset().top - e.pageY;
    if(difLeft < 50 && difLeft > -50 && difTop < 50 && difTop > -50 ){
      startMove = true;
    }
    if(startMove){
        $("#image").css({left:e.pageX, top:e.pageY});
    }
        checkCursor();
});

$(document).mouseleave(function(){
    startMove = false;
})

function checkCursor(){
    if(startMove){$('html').removeClass('showCursor');}
  else{$('html').addClass('showCursor');}
}

This added into the whole code:

  

 var startMove;
$(document).mousemove(function(e){
    var difLeft = $('#image').offset().left - e.pageX;
    var difTop = $('#image').offset().top - e.pageY;
    if(difLeft < 10 && difLeft > -10 && difTop < 10 && difTop > -10 ){
      startMove = true;
    }
    if(startMove){
    $("#image").css({left:e.pageX, top:e.pageY});
    }
checkCursor();
});

$(document).mouseleave(function(){
    startMove = false;
})

function checkCursor(){
if(startMove){$('html').removeClass('showCursor');}
  else{$('html').addClass('showCursor');}
}
    
    html {cursor: none;}
html.showCursor{cursor: default;}
#image{
position:absolute;
width:25px;
height:auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>      
    <img id="image" src="http://static.micheljansen.org/uploads/mac-osx-arrow-cursor.png"/>

Answer №2

Perhaps implementing a cheat detection system by monitoring the cursor movement could be beneficial. Here's an idea:

let x=1, y=1, percentThreshold=30; // initial cursor position...

$(document).mousemove(function(e){
    if(e.pageX > x*(1+(percentThreshold/100)) || e.pageX < x*(1-(percentThreshold/100)) || e.pageY > y*(1+(percentThreshold/100)) || e.pageY < y*(1-(percentThreshold/100))) {
        // The user is trying to cheat by moving too far from the original position
        // Take action against cheating behavior!
        console.log('Cheater detected at: '+x+'-'+y);
    } else {
       // Normal cursor movement
       x = e.pageX; y = e.pageY;
       $("#image").css({left:e.pageX, top:e.pageY});
    }
});

// Click to set the starting point... customize this based on game requirements
$(document).click(function(e) {
  x = e.pageX;
  y = e.pageY;
  console.log('Initial coordinates: ' + x + '-' + y);
});

You may need to adjust the percentage threshold (1-2% for close maze sections) based on your game setup. Finding the right balance is crucial for optimal gameplay.

Also, consider defining specific areas within the div where the cursor should remain and flagging users who move outside those boundaries as cheaters.

For further reference, check out the updated JSFiddle link here.

This revised code includes a feature to set initial coordinates via click, addressing the issue of delayed updates during fast movements.

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

Exploring date range options in Highcharts for viewing data from a specific selected date

Using HTML, JS, and Controller public function graph(Request $request) { $statistics = DiraStatistics::where('date_access',$request->date)->get(); $question_asked_sum = $statistics->sum('question_asked'); $low_ ...

Contrasting assign and modify operations on arrays

After spending 2 days searching for a bug in my angular2 project's service.ts file, I finally found it and fixed it. However, I'm still trying to understand why the working code behaves differently from the bugged one, as they appear identical to ...

What is the best way to use node.js to send a .json file via HTTP POST request?

As a beginner in these concepts, I seek guidance on how to create a script for making an HTTP POST request that sends a .json file containing an array of jsons. My resource is an npm module available at: https://github.com/request/request, along with a tut ...

What is the method to update the title dynamically in the view page source?

I've set the default $document[0].title = "My App". In the HTML, by using <title ng-bind="title"></title>, it will show up on the tab header as "My App" However, if you right click on the page and choose "view page source", it still displ ...

Do we need to eliminate the callback function once it has been called or executed in JavaScript?

My web-app regularly polls 3rd party services (such as Facebook and Twitter) for data using JSONP to avoid cross-domain issues. Here is an example of a simple request: function jsonp_callback() { // Do something } var url = 'http://some.service ...

Mobile-friendly website with consistent design across all devices

Can you help me figure out how to make my website appear at its normal size on mobile devices? I want the entire website to be visible without the need for scrolling, but still allow users to zoom in if needed. I've already tried: <meta name=" ...

Retrieve the name of the file from a given URL by using JavaScript/jQuery, even when only the directory path is

I need to extract the current filename from the URL using: $currentFile = window.location.pathname.split("/").pop(); This method functions properly when the full path looks like: http://www.yoursite.com/folder/index.php It will return index.php, index. ...

How to activate an ASP.NET LinkButton using JavaScript

I've set up a page to hide a FileUpload control, so that when a button is clicked, it displays the file upload window and automatically submits the selected file to the server. To make this work, I created two linkbuttons and a file upload control, b ...

When utilizing the "nofollow/sponsored" attribute, window.open will open in a new window as opposed to a new tab

When using a window.open link with the "nofollow" attribute, I expect it to open in a new tab. However, it opens in a new window instead. This code successfully opens in a new tab: $('.b_link').click(function (e) { e.preventDefau ...

Tips for making a draggable div come to the forefront upon clicking

I'm looking to make a jQuery draggable div come to the front when it's clicked. I came across this post, and tried creating a JsFiddle based on it, but couldn't get it to work. Any ideas on what I might be missing? Thanks! Here's the l ...

Personalizing the mat-checkbox

I'm trying to customize the checked icon in angular material mat-checkbox. Currently, it displays a white tick icon inside a colored background box, but I want to replace the tick with a cross when it is checked. After spending all day searching, I ha ...

Grab the webpage's URL by collecting the link from the src attribute of the script tag using XSLT

Can XSLT be used to extract a URL link specified within the src attribute of a script tag in an HTML file? Here is an example of the HTML file: <HTML> <BODY> <SCRIPT language="javascript" src="http://myspace.com" type="text/javascript"> ...

best practices for passing variables between multiple files within a nodejs application

// script.js var mydata = 1 module.exports = {mydata}; // file in my codebase var newData = require("../script.js") console.log(newData.mydata); // why is it undefined? I want to declare a variable as global across the entire project. I tried using ...

Shopify Inventory Dropdown Tailored to Stock Levels

I'm having an issue with my Shopify store. How can I make sure that the quantity dropdown matches the actual items in stock? For instance, if there are only 3 items available, the maximum value in the quantity dropdown should be set to 3. And if there ...

Detecting a failed Promise with an Observable in Angular 6

I've been struggling to write unit tests for error handling in an Observable that wraps a Promise. The error doesn't seem to get caught as expected. I'm creating an Observable from a Promise that should reject, and then I return it from a ...

Adding multiple text as label and sublabel in a React MUI Tooltip can be achieved by utilizing the appropriate

I'm struggling to incorporate a MaterialUI Tooltip into my React application with two separate text lines. The first line should serve as the main title, while the second line functions as a sublabel. In this screenshot provided, you can see where I ...

Is the format of this HTML tag correct?

I was provided with a code from our design department to add to a page, and since I am relatively new to the design aspect of things, I'm seeking clarification. Is this a valid tag? Also, what does <--if subcontent add rel="test1"--> mean? The c ...

A modern alternative to using the outdated `confirm` method in

I am exploring ways to prompt the user before allowing them to save a record. Let's say I have this button defined in the markup: <asp:Button ID="btnSave" runat="server" OnClick="btnSave_Click"></asp:Button> ...

How can I display multiple lines of dynamic data using JavaScript in a Highcharts chart?

I have successfully implemented a chart in jsf that dynamically generates based on user input selection from a drop-down list. However, I am now facing the challenge of enabling multiple item selections at once to display multiple lines on the chart simu ...

Is there a way to prevent autoplay on swiper only on one slide based on a specific condition?

One of the slides contains a form that opens when a button is clicked within that same slide. However, due to autoplay being enabled, the swiper continues to the next slide. I need to disable autoplay when the user clicks on the form opening button. The ...