Jump to content

Javascript / html image help


The Mighty Goat

Recommended Posts

I was wondering if there is a way to detect when a certain image is in a certain area on a page. I'm making a little game where you move a character around (which is an image), and when any part of the character is over a certain 100x200px area, it activates a function. Is this possible with JavaScript? If not, can I do it with another language that works with JavaScript and html? I'd prefer JavaScript. Thanks!

Link to comment
Share on other sites

Well, it would be drag and drop if the movement of the character was doing by clicking on it, moving the mouse and then letting go of the mouse button. It sounds more like character motion is doing through pressing keys or something similar.

Link to comment
Share on other sites

I've looked over the code and checked out the link to the JSfiddle thing. I don't know what to change in the code to make it work for me. They didn't even show how you make the image make it coordinates a variable. I'm relatively new to JavaScript so I don't a lot yet.

Edited by The Mighty Goat
Link to comment
Share on other sites

You can get the X, Y, width and height of the image using its offsetLeft, offsetTop, offsetWidth and offsetHeight properties respectively. The offsetLeft and offsetTop coordinates are relative to the image's closest positioned ancestor, also known as its offset parent.

 

I don't know if your target area is an HTML element or just an area defined by numbers. If it's an element, you can use the same properties as the image does. If it's just data then you already know the position and size.

// CHANGE THIS LINE TO A PROPER DOM REFERENCE TO YOUR IMAGE
var image = document.getElementsByTagName("img")[0];

// Information about the image's position
var imageArea {
  x: image.offsetLeft,
  y: image.offsetTop,
  width: image.offsetWidth,
  height: image.offsetHeight
};

// Information about the target area the image should intersect with
var targetArea = {
  x: 100,
  y: 100,
  width: 100,
  height: 200
};

// Collision logic here
if (imageArea.x < targetArea.x + targetArea.width &&
   imageArea.x + imageArea.width > targetArea.x &&
   imageArea.y < targetArea.y + targetArea.height &&
   imageArea.height + imageArea.y > targetArea.y) {
    // collision detected!
}

If you can't understand this, you still need to learn more about Javascript and do more research. Don't try to do a project that's beyond your capabilities.

Link to comment
Share on other sites

Sorry for keep asking questions. If I never learn this, I'll never know it.

 

I understand how it works, I'm just having problems putting it into my code. When I put it in and change it to how I think it will work for me, it makes it so I cant move the picture anymore. I also made it so it so its supposed to make an alert box appear when the collision happens, but it never appears when they collide. Even with it the if statement is in the looping function.

 

I want to show you my code but I cant paste stuff in this...?

Edited by The Mighty Goat
Link to comment
Share on other sites

What browser are you using? I don't see why you can't paste into the post editor. If the rich text editor is not working properly you can press the little light switch icon to make it a plain text editor. Be sure to wrap your code in [ code ] tags.

 

I can't help much without seeing your code.

Link to comment
Share on other sites

I'm using the normal Internet Explorer because chrome crashes my computer a couple times every day when I have it open. Copy paste works with everything else when I use this browser. Strange. I'll use chrome.

 

When you remove the four groups of code you said add, the image is movable. Try it without those bits. Also, I don't know what to put in the apostrophes in this part: document.getElementsByTagName("?")[0];

<head>
<script type='text/javascript'>
 
var image = document.getElementsByTagName("img")[0];
 
var imageArea {
x: image.offsetLeft,
y: image.offsetTop,
width: image.offsetWidth,
height: image.offsetHeight
};
 
var targetArea = {
x: 100,
y: 100,
width: 100,
height: 200
};
 
// if statement for collision is below
 
// movement vars
var xpos = 100;
var ypos = 100;
var xspeed = 1;
var yspeed = 0;
var maxSpeed = 5;
 
// boundary
var minx = 0;
var miny = 0;
var maxx = 700;
var maxy = 800;
 
// controller vars
var upPressed = 0;
var downPressed = 0;
var leftPressed = 0;
var rightPressed = 0;
 
function slowDownX()
{
  if (xspeed > 0)
    xspeed = xspeed - 1;
  if (xspeed < 0)
    xspeed = xspeed + 1;
}
 
function slowDownY()
{
  if (yspeed > 0)
    yspeed = yspeed - 1;
  if (yspeed < 0)
    yspeed = yspeed + 1;
}
 
function gameLoop()
{
 
if (imageArea.x < targetArea.x + targetArea.width &&
  imageArea.x + imageArea.width > targetArea.x &&
  imageArea.y < targetArea.y + targetArea.height &&
  imageArea.height + imageArea.y > targetArea.y) {
    alert("Collision detected");
}
 
  // change position based on speed
  xpos = Math.min(Math.max(xpos + xspeed,minx),maxx);
  ypos = Math.min(Math.max(ypos + yspeed,miny),maxy);
 
  // or, without boundaries:
  // xpos = xpos + xspeed;
  // ypos = ypos + yspeed;
 
  // change actual position
  document.getElementById('character').style.left = xpos;
  document.getElementById('character').style.top = ypos;
 
  // change speed based on keyboard events
  if (upPressed == 1)
    yspeed = Math.max(yspeed - 1,-1*maxSpeed);
  if (downPressed == 1)
    yspeed = Math.min(yspeed + 1,1*maxSpeed);
  if (rightPressed == 1)
    xspeed = Math.min(xspeed + 1,1*maxSpeed);
  if (leftPressed == 1)
    xspeed = Math.max(xspeed - 1,-1*maxSpeed);
 
  // deceleration
  if (upPressed === 0 && downPressed === 0)
     slowDownY();
  if (leftPressed === 0 && rightPressed === 0)
     slowDownX();
 
  // loop
  setTimeout("gameLoop()",10);
}
 
function keyDown(e)
{
  var code = e.keyCode ? e.keyCode : e.which;
  if (code == 38)
    upPressed = 1;
  if (code == 40)
    downPressed = 1;
  if (code == 37)
    leftPressed = 1;
  if (code == 39)
    rightPressed = 1;
}
 
function keyUp(e)
{
  var code = e.keyCode ? e.keyCode : e.which;
  if (code == 38)
    upPressed = 0;
  if (code == 40)
    downPressed = 0;
  if (code == 37)
    leftPressed = 0;
  if (code == 39)
    rightPressed = 0;
}
 
</script>
 
</head>
<body onload="gameLoop()" onkeydown="keyDown(event)" onkeyup="keyUp(event)" bgcolor='gray'>
 
<!-- The Level -->
<div style='width:900;height:900;position:absolute;left:0;top:0;background:white;'>
</div>
 
<!-- Blue Rectangle -->
<div style='width:300;height:200;position:absolute;left:450;top:550;background:blue;'>
</div>
 
<!-- Moveable Red Rectangle -->
<img id='character' src='http://images.dpchallenge.com/images_challenge/1000-1999/1238/1200/Copyrighted_Image_Reuse_Prohibited_897297.jpg' style='position:absolute;left:100;top:100;height:100;width:200;'/>
 
</body>
Edited by The Mighty Goat
Link to comment
Share on other sites

Javascript runs as soon as it has loaded. That means that the image has not yet loaded. You should load the script after the rest of the document, so that all the HTML elements are already available. It would be more organized to have your Javascript in an external file.

 

You're not updating the imageArea object in the game loop, so nothing is ever going to change. It only contains the values of the image the moment it was first assigned.

 

For the sake of efficiency, don't execute strings in your setTimeout() call. Pass a function reference instead:

setTimeout(gameLoop, 10);

10 milliseconds is very short for an interval, that's expecting the browser to do the operations 100 times per second. The browser's normal refresh rate is usually 60 frames per second, so updating more frequently than that is pointless.

Link to comment
Share on other sites

I copied the movable image code a little while ago because I didn't know how to make movable images. I mostly understand it now. I know what to change to make it how a want. The string in the loop and the 10 millisecond repeat time was part of it. I'll try what you said. Thanks :)

 

I don't know how to make a file access the JavaScript in an external file but I guess I can go research that.

 

Lastly, I still don't know what to put in the apostrophes in this part: document.getElementsByTagName("?")[0];

Link to comment
Share on other sites

You should read the Javascript tutorial again, especially the HTML DOM part of the tutorial: http://www.w3schools.com/js/js_htmldom.asp

 

getElementsByTagName() and other methods are explained there. What you need to do is access your image element. If you understand HTML DOM you should know how to do that.

Link to comment
Share on other sites

---> I found out you can only use external files if you have a website or something. I'm just writing scripts and opening them in the internet to play them. What can I do to make the JavaScript load a bit later?

 

---> I moved the if statement into the loop, but I still cant move the image anymore.

<html>
<head>
<script type='text/javascript'>
 
var image = document.getElementsByTagName("img")[0];
 
var targetArea = {
x: 350,
y: 450,
width: 300,
height: 300
};
 
// movement vars
var xpos = 50;
var ypos = 50;
var xspeed = 1;
var yspeed = 0;
var maxSpeed = 5;
 
// boundary
var minx = 0;
var miny = 0;
var maxx = 700;
var maxy = 800;
 
// controller vars
var upPressed = 0;
var downPressed = 0;
var leftPressed = 0;
var rightPressed = 0;
 
function slowDownX()
{
  if (xspeed > 0)
    xspeed = xspeed - 1;
  if (xspeed < 0)
    xspeed = xspeed + 1;
}
 
function slowDownY()
{
  if (yspeed > 0)
    yspeed = yspeed - 1;
  if (yspeed < 0)
    yspeed = yspeed + 1;
}
 
function gameLoop()
{
 
   var imageArea {
   x: image.offsetLeft,
   y: image.offsetTop,
   width: image.offsetWidth,
   height: image.offsetHeight
   };
 
   if (imageArea.x < targetArea.x + targetArea.width &&
      imageArea.x + imageArea.width > targetArea.x &&
      imageArea.y < targetArea.y + targetArea.height &&
      imageArea.height + imageArea.y > targetArea.y) {
         alert("Collision");
   }
 
  // change position based on speed
  xpos = Math.min(Math.max(xpos + xspeed,minx),maxx);
  ypos = Math.min(Math.max(ypos + yspeed,miny),maxy);
 
  // or, without boundaries:
  // xpos = xpos + xspeed;
  // ypos = ypos + yspeed;
 
  // change actual position
  document.getElementById('character').style.left = xpos;
  document.getElementById('character').style.top = ypos;
 
  // change speed based on keyboard events
  if (upPressed == 1)
    yspeed = Math.max(yspeed - 1,-1*maxSpeed);
  if (downPressed == 1)
    yspeed = Math.min(yspeed + 1,1*maxSpeed)
  if (rightPressed == 1)
    xspeed = Math.min(xspeed + 1,1*maxSpeed);
  if (leftPressed == 1)
    xspeed = Math.max(xspeed - 1,-1*maxSpeed);
 
  // deceleration
  if (upPressed == 0 && downPressed == 0)
     slowDownY();
  if (leftPressed == 0 && rightPressed == 0)
     slowDownX();
 
  // loop
  setTimeout("gameLoop()",20);
}
 
function keyDown(e)
{
  var code = e.keyCode ? e.keyCode : e.which;   // 38,40,37,39
  if (code == 87)
    upPressed = 1;
  if (code == 83)
    downPressed = 1;
  if (code == 65)
    leftPressed = 1;
  if (code == 68)
    rightPressed = 1;
}
 
function keyUp(e)
{
  var code = e.keyCode ? e.keyCode : e.which;
  if (code == 87)
    upPressed = 0;
  if (code == 83)
    downPressed = 0;
  if (code == 65)
    leftPressed = 0;
  if (code == 68)
    rightPressed = 0;
}
 
</script>
 
</head>
 
<body onload="gameLoop()" onkeydown="keyDown(event)" onkeyup="keyUp(event)" bgcolor='gray'>
 
   <!-- The Level -->
   <div style='width:900;height:900;position:absolute;left:0;top:0;background:white;'>
   </div>
 
   <!-- The Blue Area -->
   <div style='width:300;height:300;position:absolute;left:350;top:450;background:blue;'>
   </div>
 
   <!-- The Character -->
   <img id='character' src='http://images.dpchallenge.com/images_challenge/1000-1999/1238/1200/Copyrighted_Image_Reuse_Prohibited_897297.jpg' style='position:absolute;left:50;top:50;height:100;width:200;'/>
 
</body>
 
</html>
Edited by The Mighty Goat
Link to comment
Share on other sites

You can use external scripts on your local computer.

 

Just put the Javascript code in a file called "script.js" in the same directory as your HTML file and then use this code to include it:

<script src="script.js"></script>

Now, your Javascript is running too early, the HTML has not loaded yet. Move all your Javascript to the very bottom of the document right before the closing </body> tag.

Link to comment
Share on other sites

I just did the biggest face-palm ever. I did what you said and wondered why it wasn't working, so I put each part in at a time so see which was broken, and then when I added the targetArea variable, I didn't work. I looked at it and within 2 seconds, I realized it didn't have the equal sign. lol

 

Anyway, ITS WORKING!!! Thanks so much. :) :) :)

 

One more question: to activate a function in an if statement, would you do this?

if (variable = 1) {
    myFunction()
}
Edited by The Mighty Goat
Link to comment
Share on other sites

 

One more question: to activate a function in an if statement, would you do this?

if (variable = 1) { 
    myFunction();
}

 

The above seems pointless to me. What you will more commonly see is the situation below...

while (variable = someFunc()) { // truthy value is assigned
    
// use variable

}
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...