Jump to content

vmars316

Members
  • Posts

    480
  • Joined

  • Last visited

Posts posted by vmars316

  1. W3Schools doesn't have a tutorial for it. You can find information about it on the Mozilla Developer Network: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

     

    The difference between requestAnimationFrame() and setInterval/setTimeout is that requestAnimationFrame() has a variable interval, so you need to use the timestamp provided in the function to calculate values.

    Thanks ,

    In the info above , they mention a 'timestamp' .

    Is timestamp absolutely necessary .

     

    Here http://bencentra.com/canvas/canvas2.html

    He has an example without any timestamp .

    Is there a default value involved ?

    <!DOCTYPE HTML>
    <html>
    <head>
    <style>
    * {
    font-family: Calibri, Arial, sans-serif;
    }
    .center {
    text-align: center;
    }
    #mycanvas {
    display: block;
    width: 600px;
    height: 400px;
    margin: auto;
    border: 1px solid black;
    }
    button {
    font-size: 1em;
    }
    .pre {
    font-family: monospace;
    }
    #frames {
    font-weight: bold;
    }
    </style>
    </head>
    <body>
    <h1 class="center">Animation! Yeah!</h1>
    <p class="center">Playing around with <span class="pre">requestAnimationFrame();</span></p>
    <div id="buttons" class="center">
    <button type="button" onclick="start();">Start</button>
    <button type="button" onclick="stop();">Stop</button>
    <button type="button" onclick="erase();">Erase</button>
    </div>
    <p class="center">Erase on mouseover: <input type="checkbox" id="check"/></p>
    <canvas id="mycanvas" width="600" height="400">Sorry, bro.</canvas>
    <p class="center"><span id="frames">0</span> frames have been rendered.</p>
    <script>
    // Handles to DOM elements
    var f = document.getElementById("frames");
    var ch = document.getElementById("check");
    // Set up the canvas
    var c = document.getElementById("mycanvas");
    var ctx = c.getContext("2d");
    var gid;
    var frameCount = 0;
    var iRed = 255;
    var iGreen = 0;
    var iBlue = 0;
    var inc = 4;
    // Mouse over to erase the canvas
    c.addEventListener("mousemove", function (e) {
    if (ch.checked) {
    var rect = c.getBoundingClientRect();
    ctx.fillStyle = "#FFFFFF";
    ctx.beginPath();
    ctx.arc(e.clientX - rect.left, e.clientY - rect.top, 35, 0, 360, false);
    ctx.fill();
    }
    });
    // Clear the canvas
    function erase() {
    ctx.fillStyle = "#FFFFFF";
    ctx.fillRect(0, 0, 600, 400);
    }
    // Run a frame of animation
    function animate() {
    var r = Math.round(Math.random() * 20) + 5;
    var x = Math.round(Math.random() * c.width);
    var y = Math.round(Math.random() * c.height);
    //setRandomColor();
    incrementColor();
    ctx.beginPath();
    ctx.arc(x,y,r, 0, 360, false);
    ctx.fill();
    gid = requestAnimationFrame(animate);
    f.innerHTML = frameCount++;
    }
    function setRandomColor() {
    var red = Math.floor(Math.random() * 255);
    var green = Math.floor(Math.random() * 255);
    var blue = Math.floor(Math.random() * 255);
    ctx.fillStyle = "rgb("+red+","+green+","+blue+")";
    }
    function incrementColor() {
    if (iRed > 250 && iGreen <= 250 && iBlue <= 5) {
    iGreen += inc;
    }
    else if (iRed > 5 && iGreen > 250 && iBlue <= 5) {
    iRed =- inc;
    }
    else if (iRed <= 5 && iGreen > 250 && iBlue <= 250) {
    iBlue += inc;
    }
    else if (iRed <= 5 && iGreen > 5 && iBlue > 250) {
    iGreen -= inc;
    }
    else if (iRed <= 250 && iGreen <= 5 && iBlue > 250) {
    iRed += inc;
    }
    else {
    iBlue -= inc;
    }
    ctx.fillStyle = "rgb("+iRed+","+iGreen+","+iBlue+")";
    }
    // Start animation
    function start() {
    console.log("animating");
    animate();
    }
    // Stop animation
    function stop() {
    console.log("stopping");
    cancelAnimationFrame(gid);
    }
    </script>
    </body>
    </html>

     

     

  2.  

    • Indent your code properly
    • Don't use <form> tags if you're not submitting anything to the server
    • Keep track of all your timers
    • You have to use proper DOM methods to access elements like getElementById() and getElementsByTagName(). formName.elementName is non-standard and may not work properly in all browsers.
    • Check the Javascript reference for any functions that may help you. Number.toFixed() simplifies the code a lot.
    • Try to keep your code as short and simple as possible.

    Read this and try to understand how it works. It should be easy because I've cut out a whole lot of stuff from it and made it really short:

    <fieldset>  <label>    <span>Seconds:</span>    <input type="text" id="counter">  </label></fieldset><fieldset>  <button id="start">Start</button>  <button id="stop">Stop</button></fieldset><script type="text/javascript">// HTML elements we're going to usevar startButton = document.getElementById("start");var stopButton = document.getElementById("stop");var display = document.getElementById("counter");var timeout; // Global variable for clearTimeout();var startTime; // Global variable to remember when the timer started// Event handlersdocument.getElementById('start').onclick = start;document.getElementById('stop').onclick = stop;// Start the timerfunction start() {  startTime = (new Date()).getTime();  instance();} // Stop the timer function stop() {  if(timeout) {    clearTimeout(timeout);    timeout = null;  }}// Call this on each intervalfunction instance() {  elapsed = ((new Date()).getTime() - startTime) / 1000;  display.value = elapsed.toFixed(1); // Remember that "display" was defined at the beginning of the script  timeout = window.setTimeout(instance, 50);}</script>

    Actually , I am searching for Posts that contain 'requestAnimationFrame' .

     

    Just curious , why do people show code all on one line ?

    To me it is downright unpleasant , to have to copy/paste ,

    then edit code into one statement per line .

    Or is there a way to unravel code into multilines ,

    that I don't know about ?

    Thanks

  3. Hello & Thanks ,

    I am having trouble with my phone version of BenghaziGame .

     

    My viewport :

    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

     

    Also , I changed the camvas dimensions from this:

    <canvas id="canvas" width="800" height="550" style="background-color:#992D2D"></canvas>

    to this:

    <canvas id="canvas" width="360" height="400" style="background-color:#992D2D"></canvas>

     

    And it looks like I'll need to adjust a bunch of other stuff to make it visually acceptable .

     

    Running the program on desktop , it all runs fine .

    But running same code on phone , the collision detection doesn't work ,

    and the prog runs very , very slow .

     

    I could use some recommendations on what can I tweak to improve phone

    I am running it on my Lumia 640 windows phone .

     

    http://liesandcowpies.com/ gives options to run on phone or desktop .

     

    Thanks

  4. Hello & Thanks ,
    A javascript Tutorial for BenghaziGame :
    I just wanted to let you know that I have written a
    javascript tutorial for my BenghaziGame ,
    and to thank all you folks on this Forum
    who have helped me to convert this game to javascript .
    Benghazi Game is a shoot 'em up political satire browser game .
    But instead of bullets ,
    we throw cowpies at politicians when we see them lying .
    How do we know when they are lying ?
    When their noses turn into long carrot noses , they are lying .
    The Tutorial game begins here :
    I have also posted the whole Tutorial for download here :
    My disclaimer:
    I am going to let w3schools.com do most of the heavy lifting ,
    and use their GameTutorial resources to do the explaining on specific keywords .
    Here is a list of their web pages that we will be using:
    and more as the need arises .
    Thanks...Vern

     

  5. Hello & Thanks ,

    A javascript Tutorial for BenghaziGame :


    I just wanted to let you know that I have written a

    javascript tutorial for my BenghaziGame ,

    and to thank all you folks on this Forum

    who have helped me to convert this game to javascript .


    Benghazi Game is a shoot 'em up political satire browser game .

    But instead of bullets ,

    we throw cowpies at politicians when we see them lying .

    How do we know when they are lying ?

    When their noses turn into long carrot noses , they are lying .


    The Tutorial game begins here :



    I have also posted the whole Tutorial for download here :



    My disclaimer:

    I am going to let w3schools.com do most of the heavy lifting ,

    and use their GameTutorial resources to do the explaining on specific keywords .

    Here is a list of their web pages that we will be using:










    and more as the need arises .


    Thanks...Vern

  6. Hello & Thanks ;


    Javascrtip and html are all one file :

    Prob: all buttons work fine, except for <button onmousedown="touchRightArrow" .

    the onmouseup="touchEndRight()" works fine .

    But I havent been able to figure out why <button onmousedown="touchRightArrow" isn't working .

    I need a new set of eyes to help me .

    I am happy to Post all code if necessary , but its 557 lines .



    <div id="canvasDiv" align="center" >

    <canvas id="canvas" width="800" height="550" style="background-color:#992D2D"></canvas>

    <br>

    <button onclick="myGameArea.pause()" ontouchstart="myGameArea.pause()" >Pause</button>

    <button onclick="myGameArea.play()" ontouchstart="myGameArea.play()" >Play</button>

    ___

    <button onmousedown="touchLeftArrow()" onmouseup="touchEndLeft()" ontouchstart="touchLeftArrow()" ontouchend="touchEndLeft()">MoveLeft</button>

    _

    <button onclick="touchUpArrow()" ontouchstart="touchUpArrow()">Throw</button>

    _

    <button onmousedown="touchRightArrow" onmouseup="touchEndRight()" ontouchstart="touchRightArrow" ontouchend="touchEndRight()">MoveRight</button>

    ___

    <button onclick="clearIt()" ontouchstart="clearIt()">Clear</button>

    <button onclick="quitIt()" ontouchstart="quitIt()">Quit</button>

    </div>


    //

    function touchRightArrow() {

    alert("function touchRightArrow() {");

    thrower.directionX = 1;

    thrower.moveMe = true ;

    if (thrower.x > canvas.width -40) { thrower.moveMe = false ; }

    }

    //

    function touchEndRight() {

    //alert("function touchEndRight() {");

    rightPressed = false ;

    thrower.moveMe = false ;

    drawThrower();

    }

    //


  7. Hello ;


    I wrote a browser game in Enchant.js , where I did some collisions .

    It is contained in this .zip file :


    The file you are probable most interested is this one :

    BenghaziGameTest.js

    I stopped using enchantjs because they apparently stopped developing it .


    So I rewrote it in Phaser , here :


    Didn't care for Phaser too much . It is so laaarge .


    So I rewrote it in Quick.js , here :


    Runs great , but the DOCs weren't very good .


    Then I thought 'why keep fiddling with all these languages .

    Since they are all based on javascript , why not just learn javascript .'

    So I am writing it in javascript here :


    It is almost complete . Just having trouble with the 'MoveRight' button .


    The folks on this Forum are awesome !!!


    Anyways , take a look at enchant.js code :



    Happy Trails...


  8. Hey dsonesuk , Thanks a lot !

    I am studying it a bit .

    <!DOCTYPE html>
    <head>
    <!--
    rosemary & lemongrass
    -->
    </HEAD>
    <body>
    <div>
    <button onclick="preload_audio_files(My_audio_files)">preload_audio_files(My_audio_files)</button>
    <button onclick="playMp3()">playMp3()</button>
    </div>
    <script type='text/javascript'>
    var My_audio_files = ["sounds/ObamaOnVideo.mp3", "sounds/oops.mp3"];
    var new_Audio_files = [];
    var numAudios = 0;
    function preload_audio_files(arr_files)
    {
    for (var i = 0; i < arr_files.length; i++)
    { new_Audio_files = new Audio();
    new_Audio_files.src = My_audio_files;
    new_Audio_files.preload = "auto";
    numAudios = i;
    }
    alert("new_Audio_files[0]= " + new_Audio_files[0]);
    }
    // preload_audio_files(My_audio_files);
    function playAudio(playThis) {
    playThis.play();
    }
    //
    function playMp3() {
    playAudio(new_Audio_files[0]); // the first song
    setTimeout(function() { playAudio(new_Audio_files[1]); }, 2000);
    }
    //call playAudio function with relative new_Audio_files[] index reference matching My_audio_files index of files
    // playAudio(new_Audio_files[0]); // the first song
    // playAudio(new_Audio_files[1]); // the second song
    </script>
    </body>
    </html>

     

     

  9. Thanks Folks ,
    The code is for a computer game:

    Here is the code to play sound:
    for (var i = cowpies.length - 1; i >= 0; i--) {
    thisPie = i;
    if (cowpies[thisPie].idActive) {
    if(this.visible) { // yes , do collision CK
    if (cowpies[thisPie].y < this.y + this.height && cowpies[thisPie].y + cowpies[thisPie].height > this.y)
    { if (cowpies[thisPie].x < this.x + this.width && cowpies[thisPie].x + cowpies[thisPie].width > this.x )
    { // alert("YES , a collision has occurred");
    thisIdTag = this.idTag ;
    var yesTruth = thisIdTag.startsWith("truth");
    var yesLies = thisIdTag.startsWith("lies");
    //alert("yesTruth= "+ yesTruth + "\n yesLies= " + yesLies);
    if(yesTruth) { switch(this.idTag) {
    case "truth01": this.visible = false ; truth01.tripsCnt =0 ; lies01.visible=true ;
    alert("case 'truth01': ") ;
    playAudio("sounds/oops.mp3"); break ;
    // case "truth02": this.visible = false ; lies02.visible = true ; break ;
    // case "truth03": this.visible = false ; lies03.visible = true ; break ;
    // case "truth04": this.visible = false ; lies04.visible = true ; break ;
    }
    }
    // play sound & keep score oops hit + total shots oops.mp3
    if (yesLies){ switch(this.idTag) {
    case "lies01":
    lies01.tripsCnt =0;
    truth01.speedX=1 ; idTag = "truth01" ; lies01.visible=false ;
    truth01.visible=true ; alert("case 'lies01': ") ;
    playAudio("sounds/ObamaOnVideo.mp3"); break ;
    // case "lies02": this.visible = false ; truth02.visible = true ; break ;
    // case "lies03": this.visible = false ; truth03.visible = true ; break ;
    // case "lies04": this.visible = false ; truth04.visible = true ; break ;
    }
    // play sound & keep score good hit + total shots
    }
    cowpies.splice(thisPie,1); //alert("cowpies.length= "+ cowpies.length);
    }
    }
    }
    }
    } // endof or (var i = cowpies.length - 1

     

    Here is line to play sound:
    playAudio("sounds/ObamaOnVideo.mp3");

     

    and here is the 'playAudio function':
    function playAudio(playThis) {
    var audio = new Audio(playThis);
    }

     

    Everytime there is a collision between a cowpie and a person ,
    I need to play/replay that sound .
    So , I need to know 'how to replay sound from cache' ,
    without any controls visible .
    Thanks
  10. Ooooh... , Thanks Newbie:
    In the mean time I discovered the format below :

    playAudio("sounds/ObamaOnVideo.mp3");
    function playAudio(playThis) {
    var audio = new Audio(playThis);
    audio.play();
    }

     

     

    My question on that is ;
    Does the playThis file remain in memory ?
    Or does it get released after the audio.play(); ?
    If it remains in memory , how can I access it multiple times ?
    Thanks
  11. What I am passing into playAudio is this:

    "sounds/ObamaOnVideo.mp3"

     

     

    And when I code the following , I get same error:

    function playAudio() {
    <audio>
    <source src="sounds/ObamaOnVideo.mp3" type="audio/mpeg">
    Your browser does not support the audio tag.
    </audio>
    }

     

    Thanks

  12. Hello & Thanks ,
    I am getting an error :
    Uncaught SyntaxError: Unexpected token <
    on the line <audio src=playThis>
    in this code :
    function playAudio(playThis) {
    <audio src=playThis>
    <p>Your browser does not support the <code>audio</code> element </p>
    </audio>
    }

     

     

    Pls , what am I doing wrong ?

    Thanks

  13. Hello & Thanks ,

    I am getting the following error:

     

    Uncaught ReferenceError: thruth01 is not defined

    on this statement:

    if(cowpie.y > truth01.y && cowpie.y < thruth01.y + 64 || cowpie.y > truth02.y && cowpie.y < thruth02.y + 64 ) {
    alert("truth cowpie collision !")
    }

     

    function startGame() {

    //
    truth01 = new TargetImages();
    truth01.idTag = "truth01";
    truth01.x = 0;
    truth01.y = 40;
    truth01.width = 64;
    truth01.height = 64;
    truth01.speedX = 1;
    truth01.speedY = 0;
    truth01.tripsCnt =0;
    truth01.tripsMax=2;
    truth01.visible = true;
    truth01.directionX = 1;
    //
    lies01 = new TargetImages();
    lies01.idTag = "lies01";
    lies01.x = 0;
    lies01.y = 40;
    lies01.width = 64;
    lies01.height = 64;
    lies01.speedX = 1;
    lies01.speedY = 0;
    lies01.tripsCnt =0;
    lies01.tripsMax=2;
    lies01.visible = false;
    lies01.directionX = 1;
    //
    myGameArea.start();
    }

    Whole code is here:

     

    <!DOCTYPE html>

    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta charset="utf-8" />
    <title>Th,Co,Tr</title>
    <style>
    canvas {
    border:1px solid #d3d3d3;
    background-color: #f1f1f1;
    }
    #assets {
    visibility: hidden;
    }
    </style>
    </head>
    <body onload="startGame()">
    fromWhere= <span id="fromWhere">fromWhere</span><br>
    idTag= <span id="idTag">idTag</span><br>
    this.idTag= <span id="thisIdTag">this.idTag</span><br>
    this.visible= <span id="this.visible"> this.visible</span><br>
    this.tripsMax= <span id="this.tripsMax"> this.tripsMax</span><br>
    this.tripsCnt= <span id="this.tripsCnt"> this.tripsCnt</span><br>
    this.directionX= <span id="this.directionX"> this.directionX</span><br>
    this.x= <span id="this.x"> this.x</span><br>
    thrower x,y,w,h= <span id="thrower.xywh">thrower.x,y,w,h</span><br>
    <div align="center">
    <table style="text-align: left; width: 100%;" border="0"
    cellpadding="2" cellspacing="2">
    <tbody>
    <tr>
    <td style="width:70%";><p id="traceMsg">traceLog goes here:</p>
    </td>
    <td style="width:30%";> <canvas id="canvas" width="300" height="300"></canvas>
    </td>
    </tr>
    </tbody>
    </table>
    </div>
    <div id="assets">
    <img id="truth01" src="sprites/truth01.png" width="64" height="64" />
    <img id="truth02" src="sprites/truth02.png" width="64" height="64" />
    <img id="lies01" src="sprites/lies01.png" width="64" height="64" />
    <img id="lies02" src="sprites/lies02.png" width="64" height="64" />
    <img id="cowpie" src="sprites/cowpie.png" width="32" height="32" />
    <img id="thrower" src="sprites/thrower.png" width="64" height="64" />
    <audio id="closeDoor" src="sounds/CloseDoor.ogg"></audio>
    </div>
    <script type='text/javascript'>
    //
    var oneTraceLine = ""; var traceYESorNO = false; var updateFor1stTime = 0;
    var fromWhere = "fromWhere"; var timesInTripsCk=0; var visible = true;
    var thisx=0; var tripsMax=0; priorTripsMax = 0;
    var thisIdTag; var thrower_xywh = ""; var resetSpeedX = 2; var z =0;
    var idTag = "truth01"; var idTagTh = "thrower"; var firstTimeInCowpieUpdate = true ;
    var idTag01 = "truth01"; // prime the pump
    var idTag02 = "truth02"; // prime the pump
    var idTag03 = "truth03"; // prime the pump
    var idTag04 = "truth04"; // prime the pump
    // var truth01; var lies01; var truth02; var lies02;
    var tripsCnt=0; var directionX=1 ; var addit = 0;
    //
    canvas = document.getElementById("canvas"); // get the canvas
    ctx = canvas.getContext('2d'); // create canvas Context;
    var allImgsCnt = 0; var idTag = "truth01"; var totalTrips = 0;
    var allImgs = [document.getElementById("truth01"),
    document.getElementById("lies01"), //,
    document.getElementById("truth02"),
    document.getElementById("lies02"),
    document.getElementById("thrower")
    ] ;
    //
    var cowpies = [];
    var cowpieImg = document.getElementById("cowpie");
    //
    var Thrower = function () {
    var self = this;
    this.idTag = 'thrower';
    this.x = (canvas.width / 2) -30;
    this.y = canvas.height - 64;
    this.width= 64;
    this.height = 64;
    this.speedX = 2 ;
    this.speedY = 0;
    this.visible = true;
    this.directionX = 9;
    this.moveMe = false ;
    this.update = function() {
    if(self.x < 2 || self.x > (canvas.width -50)) {self.x = (canvas.width / 2) -30; }
    self.x = self.x + (self.speedX * self.directionX); // always = +1 or -1 }
    self.speedX = resetSpeedX ;
    self.moveMe = false ;
    }
    }
    //
    thrower = new Thrower();
    thrower.idTag ; // = 'thrower';
    thrower.x ; // = 0;
    thrower.y ; // = canvas.height - 64;
    thrower.width ; // = 64;
    thrower.height ; // = 64;
    thrower.speedX ; // = 1;
    thrower.speedY ; // = 0;
    thrower.visible ; // = true ;
    thrower.directionX ; // = 1;
    thrower.moveMe ; // = true ;
    //
    var Cowpie = function () {
    var self = this;
    this.idTag = 'cowpie';
    this.idActive = true ;
    this.x = thrower.x;
    this.y = thrower.y;
    this.width= 32;
    this.height = 32;
    this.speedX = 0;
    this.speedY = 3;
    this.visible = true;
    this.directionY = -1;
    this.moveMe = false ;
    }
    //
    Cowpie.prototype.update = function() {
    var watchi = 0;
    if (firstTimeInCowpieUpdate && cowpies.length == 0) {cowpies.push(cowpie = new Cowpie); firstTimeInCowpieUpdate = false;}
    for (var i = cowpies.length - 1; i >= 0; i--) {
    watchi = i;
    if (cowpies[watchi].idActive) { // alert("cowpie.update " + watchi + " 4 cowpies[watchi].idActive= " + cowpies[watchi].idActive);
    cowpies[watchi].y = cowpies[watchi].y+ (cowpies[watchi].speedY * cowpies[watchi].directionY); // always -1 }
    ctx.drawImage(cowpieImg, cowpies[watchi].x, cowpies[watchi].y, cowpies[watchi].width, cowpies[watchi].height);
    /*out of bounds?*/ if(cowpies[watchi].y < 1) { cowpies[watchi].idActive = false ; } // out of bounds check
    /*any collisions ?*/ // collisionCk();
    if(cowpie.y > truth01.y && cowpie.y < thruth01.y + 64 || cowpie.y > truth02.y && cowpie.y < thruth02.y + 64 ) {
    alert("truth cowpie collision !")
    }
    if(cowpie.y > lies01.y && cowpie.y < lies01.y +64 || cowpie.y > lies02.y && cowpie.y < lies02.y +64 ) {
    alert("lies cowpie collision !")
    }
    if(!cowpies[watchi].idActive) { // alert("cowpie.update " + watchi + " 5 cowpies[watchi].idActive= " + cowpies[watchi].idActive);
    cowpies.splice(i,1);
    }
    }
    cowpieCount = cowpies.length;
    }
    }
    //
    cowpie = new Cowpie();
    cowpie.idTag = 'cowpie';
    //
    function startGame() {
    //
    truth01 = new TargetImages();
    truth01.idTag = "truth01";
    truth01.x = 0;
    truth01.y = 40;
    truth01.width = 64;
    truth01.height = 64;
    truth01.speedX = 1;
    truth01.speedY = 0;
    truth01.tripsCnt =0;
    truth01.tripsMax=2;
    truth01.visible = true;
    truth01.directionX = 1;
    //
    lies01 = new TargetImages();
    lies01.idTag = "lies01";
    lies01.x = 0;
    lies01.y = 40;
    lies01.width = 64;
    lies01.height = 64;
    lies01.speedX = 1;
    lies01.speedY = 0;
    lies01.tripsCnt =0;
    lies01.tripsMax=2;
    lies01.visible = false;
    lies01.directionX = 1;
    //
    myGameArea.start();
    }
    var TargetImages = (function () {
    function TargetImages() {
    this.nameTag = 'truth01'
    this.x = 0;
    this.y = 0;
    this.width= 32;
    this.height = 32;
    this.speedX = 1;
    this.speedY = 0;
    this.tripsCnt =0;
    this.tripsMax=2;
    this.visible = true;
    this.directionX = 1;
    this.update = function() {
    ctx.drawImage(allImgs[allImgsCnt], this.x, this.y, this.width, this.height);
    this.x = this.x + (this.speedX * this.directionX); // always = +1 or -1
    document.getElementById("this.x").innerHTML = this.x;
    idTag = this.idTag;
    if(this.x > canvas.width - 2) {this.directionX = -1; // change direction
    this.x = canvas.width - 2;
    this.tripsCnt++; totalTrips++;
    fromWhere = "(this.x > canvas.width)";
    thisIdTag = this.idTag; visible = this.visible; tripsMax = this.tripsMax; tripsCnt = this.tripsCnt; directionX = this.directionX; thisx = this.x;
    alertStats();
    }
    if(this.x < -64 ) {this.directionX = 1; // change direction
    this.x = 0;
    this.tripsCnt++; totalTrips++;
    fromWhere = "if(this.x < -63 )";
    thisIdTag = this.idTag; visible = this.visible; tripsMax = this.tripsMax; tripsCnt = this.tripsCnt; directionX = this.directionX; thisx = this.x;
    alertStats();
    }
    if(this.tripsCnt > this.tripsMax) {
    if(this.idTag == "truth01") {this.speedX = 0; truth01.tripsCnt =0;
    // lies01.speedX=1 ; idTag01 = "lies01"; this.visible=false ; lies01.visible=true ;
    lies01.speedX=1 ; idTag = "lies01"; this.visible=false ; lies01.visible=true ;
    }
    if(this.idTag == "lies01") {this.speedX = 0; lies01.tripsCnt =0;
    truth01.speedX=1 ; idTag = "truth01" ; lies01.visible=false ; truth01.visible=true ;
    }
    fromWhere = "if(this.tripsCnt > this.tripsMax )";
    thisIdTag = this.idTag; visible = this.visible; tripsMax = this.tripsMax; tripsCnt = this.tripsCnt; directionX = this.directionX; thisx = this.x;
    alertStats();
    // alert('LEAVING TRIPsMAX: truth01.visible= ' + this.visible + ' , lies01.visible= ' + lies01.visible + ' \ntotalTripsCnt= ' + totalTrips);
    }
    }
    return TargetImages;
    })();
    function collisionCk() {
    }
    //
    function alertStats() {
    document.getElementById("fromWhere").innerHTML = fromWhere;
    document.getElementById("idTag").innerHTML = idTag;
    document.getElementById("thisIdTag").innerHTML = thisIdTag;
    document.getElementById("this.visible").innerHTML = visible;
    document.getElementById("this.tripsMax").innerHTML = tripsMax;
    document.getElementById("this.tripsCnt").innerHTML = tripsCnt;
    document.getElementById("this.directionX").innerHTML = directionX ;
    document.getElementById("this.x").innerHTML = thisx;
    document.getElementById("thrower.xywh").innerHTML = thrower.x;
    }
    //
    function updateGameArea() {
    myGameArea.clear();
    allImgsCnt = 0;
    if(idTag == "truth01" && truth01.visible) { truth01.update();
    }
    allImgsCnt = 1;
    if(idTag == "lies01" && lies01.visible) { lies01.update();
    }
    allImgsCnt = 4;
    if(thrower.visible) { // alert("thrower.visible");
    if(thrower.moveMe) {thrower.update();}
    ctx.drawImage(allImgs[allImgsCnt], thrower.x, thrower.y, thrower.width, thrower.height);
    thisIdTag = thrower.idTag; visible = this.visible; tripsMax = this.tripsMax;
    tripsCnt = this.tripsCnt; directionX = this.directionX; thisx = this.x;
    thrower_xywh = (thrower.x +" , "+ thrower.y +" , "+ thrower.width +" , "+ thrower.height);
    alertStats();
    };
    cowpie.update();
    } // End OF function updateGameArea()
    //
    var myGameArea = {
    start : function() {
    thrower.moveMe = false ;
    interval = setInterval(updateGameArea, 5);
    // updateGameArea();
    },
    clear : function() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    },
    stop : function() {
    clearInterval(this.interval);
    }
    }
    //
    document.addEventListener("keydown", keyDownHandler, false);
    document.addEventListener("keyup", keyUpHandler, false);
    document.addEventListener("mousemove", mouseMoveHandler, false);
    //
    function keyDownHandler(e) {
    // alert(" 1 cowpies.length - 1 " + z);
    if(e.keyCode == 39 || event.keyCode == 68) { // move right D or --->
    thrower.directionX = 9;
    thrower.moveMe = true;
    }
    if(e.keyCode == 37 || event.keyCode == 65) { // move left A or <---
    thrower.directionX = -9;
    thrower.moveMe = true;
    }
    if(e.keyCode == 87 || event.keyCode == 38) { // shoot = W or upArrow
    // alert("if(e.keyCode == 87 ||");
    z= 0 ;
    cowpies.push(cowpie = new Cowpie); // add cowpie in last position
    z = cowpies.length - 1; // put last pie created position into z
    // alert(" 2 cowpies.length - 1 " + z);
    ctx.drawImage(cowpieImg, cowpies[z].x, cowpies[z].y, cowpies[z].width, cowpies[z].height);
    } // END OF for (var i =
    }
    //
    function keyUpHandler(e) {
    if(e.keyCode == 38 || event.keyCode == 87) {
    rightPressed = false;
    }
    else if(e.keyCode == 40 || event.keyCode == 83) {
    leftPressed = false;
    }
    }
    function mouseMoveHandler(e) {
    var relativeX = e.clientX - canvas.offsetLeft;
    // if(relativeX > 0 && relativeX < canvas.width) {
    // paddleX = relativeX - paddleWidth/2;
    // }
    }
    //
    //
    </script>
    </body>
    </html>

    I think it has to do with the placement of :

    truth01 = new TargetImages();

    But I can't figure out where it should go .

    Thanks

  14. Thanks ,

    Yes , I am having difficulty with the distinction between


    1) cowpie the image (cowpie.png)

    2) var cowpie = new Cowpie();

    3) var cowpies = [document.getElementById("cowpie")];


    I haven't worked with multiple copies of an image , along with multiple copies of same definition .


    It looks like I need two arrays ,

    one for multiple cowpie.png's

    and one for the definitions of each of the cowpie.png


    Is that correct ?

  15. Hello & Thanks ,

    I am getting this error:

    Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(HTMLImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap)'

     

    on this line:

             ctx.drawImage(cowpies[i], cowpies[i].x, cowpies[i].y, cowpies[i].width, cowpies[i].height); 
     

    I got no error msg from the 'onload' .

    Haven't figured out what I am doing wrong .

    Pls , take a look .

     

    <!DOCTYPE html>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta charset="utf-8" />
    <title>move pieThrower</title>
    <style>
    canvas {
    border:1px solid #d3d3d3;
    background-color: #f1f1f1;
    }
    #assets {
    visibility: hidden;
    }
    </style>
    </head>
    <body onload="startGame()">
    <div align="center">
    <table style="text-align: left; width: 100%;" border="0"
    cellpadding="2" cellspacing="2">
    <tbody>
    <tr>
    <td style="width:70%";><p id="traceMsg">traceLog goes here:</p>
    </td>
    <td style="width:30%";> <canvas id="canvas" width="300" height="300"></canvas>
    </td>
    </tr>
    </tbody>
    </table>
    </div>
    <div id="assets">
    <img id="cowpie" src="sprites/cowpie.png" width="32" height="32" />
    </div>
    <script type='text/javascript'>
    //
    var firstTimeInCowpieUpdate = true ; var watchi = 0;
    canvas = document.getElementById("canvas"); // get the canvas
    ctx = canvas.getContext('2d'); // create canvas Context;
    var cowpies = [document.getElementById("cowpie")];
    //
    var Cowpie = function () {
    var self = this;
    this.idTag = 'cowpie';
    this.idActive = true ;
    this.x = 150;
    this.y = 150;
    this.width= 64;
    this.height = 64;
    this.speedX = 0;
    this.speedY = 5;
    this.visible = true;
    this.directionY = -1;
    this.moveMe = false ;
    }
    //
    Cowpie.prototype.update = function() {
    alert("cowpie.update " + watchi + " 0 cowpies.length= " + cowpies.length);
    }
    //
    var cowpie = new Cowpie();
    //
    function startGame() {
    watchi = 0 ;
    alert(i + "1 cowpies.length= " + cowpies.length);
    cowpies.push(new Cowpie);
    document.getElementById("traceMsg").innerHTML = cowpies[0];
    for (var i = cowpies.length - 1; i >= 0; i--) {
    watchi = i;
    alert(i + " 2 cowpies.length= " + cowpies.length);
    if (!cowpies.idActive) { cowpies.splice(i,1);
    alert(i + " 3 !cowpies.idActive= " + cowpies.idActive)}
    if (cowpies.idActive) {alert(i + " 4 cowpies.idActive= " + cowpies.idActive)}
    cowpies.push(cowpie =new Cowpie); // add cowpie
    ctx.drawImage(cowpies, cowpies.x, cowpies.y, cowpies.width, cowpies.height);
    alert(i + " 5 cowpies.length= " + cowpies.length);
    //
    } // for (var i =
    }
    //
    //
    </script>
    </body>

     

    </html>
    
    
    						
  16. Thanks ,

    this line was problem :

    Cowpie.prototype.update = function() {

    then this one :

    var cowpie = new Cowpie();

     

    I'll try to do better next time .

     

    A related question , I don't have much experience with arrays :

    Array defined like this : var cowpies = [document.getElementById("cowpie")];

    I am getting a '174 Uncaught TypeError: Cannot read property 'idActive' of undefined'

    on this line :

    if (!cowpies.cowpie.idActive) {cowpies.pop(cowpie);};

    in :

            if(e.keyCode == 87 || event.keyCode == 38) { // shoot W or upArrow
    //            check cowpies array if idActive = false  Delete item  
    //            1st active cowpie already set up in   function startGame()
            for (var i = cowpies.length - 1; i >= 0; i--) {
    		     cowpiesCount = i ;
                if (!cowpies[i].cowpie.idActive) {cowpies[i].pop(cowpie);}; 
    		    alert("cowpies[i].cowpie.idActive = " + i + "  "+ cowpies[i].cowpie.idActive );
        }			
    		     cowpie = new Cowpie;
    			 cowpies[i].cowpie.update;
    			 cowpies.push(cowpie);
    			
    			}
    

    I think I am messing up on the array syntax .

    Pls , what should it be ?

    Thanks

×
×
  • Create New...