• Das Erstellen neuer Accounts wurde ausgesetzt. Bei berechtigtem Interesse bitte Kontaktaufnahme über die üblichen Wege. Beste Grüße der Admin

Springende Bälle Browser (HTML5, Canvas, Javascript) wie löscht man eine Kugel?

Aldon

New member
Hallo liebes Forum!

ich bin gerade dabei ein kleines Browserprojekt abzuschließen bzw. es zu anzufertigen.
Das Ziel ist es ein Mini Browsergame zu errichten bei dem die Bälle hüpfen und vom Nutzer angeklickt werden und verschwinden sollen.
Dabei wird die Zeit gestoppt und man hat seine z.B.: 10 Kugeln die so schnell wie möglich angeklickt werden sollen.
Meine Kugeln fliegen auch umher und alles, jedoch ist es mir noch nicht gelungen eine Kugel die angeklickt wurde, zu löschen bzw. zu entfernen. :confused:
Aufgebaut ist es recht simpel HTML5 als gestaltende Oberfläche mit Canvas-Element, JavaScript zur Programmierung.
Im großen und ganz ist es zwar funktionsfähig aber ich habe es nicht geschafft zu Scripten, dass mir ein Ball/Kugel auf einen Klick verschwindet. (Nach diesem Vorbild Edit fiddle - JSFiddle).
Und die Zeit ist auch nicht optimal mit NaN (Not a Number ;D), muss irgendwas ganz kleines und triviales sein.
Wäre echt schön wenn ihr mir dabei helfen könntet. :D :cool:

Hier die Links:
http://donald95.bplaced.net/projekt/circlecatch_web.html
(hier seht ihr mal das Projekt im ganzen Umfang)

Hier die JS-Datei(BubbleGeneration2.js):
http://donald95.bplaced.net/projekt/BubbleGeneration2.js

Hier nochmal als Quelltext:
Code:
var zeichenflaeche = document.getElementById("spielCanvas");;
var ctx = zeichenflaeche.getContext("2d");
var BubbleList;
var width;
var height;
var interval_handle = null;
var deleted;
var draw_cycle = null;
var timer_cycle = null;
var time;
var cx=100;
var cy=100;
var radius = Math.random() * 100 % 11 + 10;

var Bubble = function(x, y, col) {
this.col = col;
this.radius = Math.random() * 100 % 11 + 10;
this.wert = Math.ceil(Math.random() * 100 % 10) + 1;
if (x + this.radius > width)
    x -= this.radius;
if (y + this.radius > height)
    y -= this.radius;
if (x - this.radius < 0)
    x += this.radius;
if (y - this.radius < 0)
    y += this.radius;
this.x = x;
this.y = y;
this.diffX = (Math.random() * 19) + 1;
this.diffY = (Math.random() * 19) + 1;
var length = Math.sqrt(this.diffX*this.diffX+this.diffY*this.diffY);
this.diffX = this.diffX / length;
this.diffY = this.diffY / length;

this.speed = Math.random() * 200 % 6 + 3;
}

function mouseLeft() {
  var hit = null;
  var index = -1;
  for (var i = 0; i < BubbleList.length; i++) {
    hit = hitbubble(x.mousePos, y.mousePos, BubbleList[i]);
    if (hit) {
      index = i;
    }
  }
  if (index >= 0)
    if (BubbleList[index].wert == lastremoved + 1) {
        BubbleList.splice(index , 1);
        deleted = minWert(BubbleList) - 1;
        if (BubbleList.length == 0) {
          clearInterval(timer_cycle);
          clearInterval(draw_cycle);
          endScreen();
        }
    }
}

function hitbubble(x, y, bubble) {
  var dx = Math.abs(x - bubble.x);
  var dy = Math.abs(y - bubble.y);
  var distance = dx*dx+dy*dy;
  if (distance < (bubble.radius*bubble.radius)) {
    return bubble;
  } else {
    return null;
  }
}

function mouseIsInsideCircle(mouseX, mouseY, cx, cy, radius) {
    var dx = mouseX - cx;
    var dy = mouseY - cy;
    return (dx * cx + dy * cy <= radius * radius);
}
//b.x, b.y, b.radius, 0, 2*Math.PI

function getMousePos(zeichenflaeche, evt) {

    var rect = zeichenflaeche.getBoundingClientRect();

    return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
    };

}

zeichenflaeche.addEventListener('mousemove', function (evt) {
    var mousePos = getMousePos(zeichenflaeche, evt);
    var message = 'Mouse position: ' + parseInt(mousePos.x) + ',' + parseInt(mousePos.y);
    writeMessage(zeichenflaeche, message);
}, false);


var mousePos;
function writeMessage(zeichenflaeche, message) {
    ctx.clearRect(0, 10, zeichenflaeche.width, 30);
    ctx.font = '18pt Calibri';
    ctx.fillStyle = 'black';
    ctx.fillText(message, 18, 25);
}

zeichenflaeche.addEventListener('mousedown', function (evt) {
    var mousePos = getMousePos(zeichenflaeche, evt);
    var mouseX = mousePos.x;
    var mouseY = mousePos.y;
    // if the mouse is inside the circle
    if (mouseIsInsideCircle(mouseX, mouseY, cx, cy, radius)) {

        // erase the canvas
        ctx.clearRect(0, 0, zeichenflaeche.width, zeichenflaeche.height);
    }

}, false);

function init() {
  BubbleList = new Array();
  width = zeichenflaeche.width;
  height = zeichenflaeche.height;
  erzeugeBubbleMenge(10);
  if (!interval_handle)
    interval_handle = setInterval(draw,10);
    alert("Willkommen zu Circlecatch!");
}

function draw() {
   ctx.clearRect(0, 0, width, height);
   ctx.font = "17pt Impact";
   update();
   for (var i = 0; i < BubbleList.length; i++) {
   var b = BubbleList[i];
   ctx.beginPath();
   ctx.fillStyle = b.col;
   ctx.arc(b.x, b.y, b.radius, 0, 2*Math.PI);
   ctx.fill();
   ctx.fillStyle = "#000000";
   ctx.closePath();

   var w = ctx.measureText(b.wert).width;
   var h = parseInt(ctx.font) * 0.5;
    ctx.fillText(b.wert, b.x - w / 3, b.y + h / 3);

   }
   ctx.fillstyle = "#000000";
     var min = time / 1000;
     ctx.fillText(min.toFixed(2) + " Sekunden", 0, height);

}
function update() {
        for (var i = 0; i < BubbleList.length; i++) {
        if (BubbleList[i].x + BubbleList[i].diffX * BubbleList[i].speed + BubbleList[i].radius > width || BubbleList[i].x + BubbleList[i].diffX * BubbleList[i].speed - BubbleList[i].radius < 0) {
     BubbleList[i].diffX *= -1;
}
    if (BubbleList[i].y + BubbleList[i].diffY * BubbleList[i].speed + BubbleList[i].radius > height || BubbleList[i].y + BubbleList[i].diffY * BubbleList[i].speed - BubbleList[i].radius < 0) {
       BubbleList[i].diffY *= -1;
}
     BubbleList[i].x += BubbleList[i].diffX * BubbleList[i].speed;
     BubbleList[i].y += BubbleList[i].diffY * BubbleList[i].speed;
}
}

function erzeugeEinzelneBubble() {
   var x = Math.ceil(Math.random() * width);
   var y = Math.ceil(Math.random() * height);
   var bubble = new Bubble(x, y, "#1BD2D8");
   BubbleList.push(bubble);
}
function erzeugeBubbleMenge(anzahl) {
BubbleList.splice(0, BubbleList.length);
for (var i = 0; i < anzahl; i++) {
     erzeugeEinzelneBubble();
}
}

Die HTML
HTML:
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8" name="Bouncing Balls"/>
<style type="text/css">
<!--
body {
  font: 100.01% Verdana, Arial, Helvetica, sans-serif;
}

* {
  margin:0;
  padding:0;
}

#seite {
  width: 780px;
  margin: 0 auto;
}

#header {
  background-color:lightblue;
  text-align: center;
}

#main {
  background-color: lightgreen;
}

#spiel {
  height:inherit;
}

#steuerung {
  background-color: transparent;
}

#footer {
  clear: both;
  background-color:lightblue;
}
-->
</style>

</head>
<body>
<table border="0" align="center">
<div id="seite">
  <tr>
    <th colspan="15">
    <div id="header">
        <div id="header"><h1>Circlecatch</h1></div>
  </div>
    </th>
  </tr>
  <tr>
    <td colspan="7">
         <div id="steuerung">
                 <div id="sidebar">
                         <button id="button" onclick="init()"><h3><u>Starten</u></h3></button><br>
                         <button id="button" onclick="showdescription()"><h3>Beschreibung</h3></button><br>
                         <button id="button" onclick="showsettings()"><h3>Einstellungen</h3></button><br>
                 </div>
         </div>
  </td>
    <td colspan="8">
         <div id="spiel">
                 <canvas id="spielCanvas" width="800" height="600">
                 </canvas>
         </div>
    </td>
  </tr>
  <tr>
    <td colspan="15">
         <div id="footer">
                 <p>Thomas A. Anderson ID. 0000001 </p>
         </div>
    </td>
    </tr>
</div>
</table>
</body>
<script src="http://donald95.bplaced.net//projekt//BubbleGeneration2.js"></script>
</html>

Ach und entschuldigt meine Fehler, Javascript habe ich erst angefangen zu nutzen. Also wundert euch nicht bei sehr trivialen Fehlern bzw. bei Anfängerfehlern.
 
Vielen Dank für die Freischaltung.

- - - Aktualisiert - - -

Also die Geschwindigkeit müsste jetzt besser sein.
Also langsamer.
 
Hallo Aldon, willkommen im Forum.


In deinem Skript ist einiges im argen, macht aber nix jeder fängt mal klein an.

Aldon schrieb:
Und die Zeit ist auch nicht optimal mit NaN (Not a Number ;D), muss irgendwas ganz kleines und triviales sein.
Ja, Du initialisierst eine deine varible time mit undefined var time;
dann rechnest du var min = time / 1000; undefiend durch 1000, das könnte ich auch nicht ausrechnen:p

Dann ist den Timer falsch, du möchtest doch bestimmt die Ausgabe in mm:ss. Dann würde ich wenn du die Animation startest den Timer in eine andere Funktion packen und die Ausgabe in einem innerHTML machen. Das Spart ungemein an cpu last.

Zu dem löschen der kreise:
soweit ich das sehe findet das löschen in der Funktion: mouseLeft() statt aber wo wird diese den aufgerufen?
Das
Code:
  if (mouseIsInsideCircle(mouseX, mouseY, cx, cy, radius)) {

        // erase the canvas
        ctx.clearRect(0, 0, zeichenflaeche.width, zeichenflaeche.height);
    }
brauchst du auch nicht, du rufst clearRect schon in den draw Intervall auf. Also das if wird schon noch benötig:d
Du muss nur dafür sorgen das der kreis aus dem array "BubbleList" verscheidet, dann ist es auch im canvas weg.


Leider ist gestern mein Rechner an BlueScreen of Death gestorben, sonnst hätte ich vielleicht schon ein lauffähiges Script geliefert. :grief:
 
Ja habe jetzt noch einiges korrigiert bzw. verbessert.
Die Kugeln verschwinden jetzt.
Jetzt fehlen noch Spiellogik (punkte und zeit).
Zeit wird zwar ausgegeben. Aber immernoch Fehler drin.

- - - Aktualisiert - - -

Wie gesagt die Zeit ist noch falsch...
Mache ich morgen, bin jetzt müde.

Code:
var zeichenflaeche = document.getElementById("spielCanvas");
var ctx = zeichenflaeche.getContext("2d");
var BubbleList;
var width;
var height;
var interval_handle = null;
var deleted;
var draw_cycle = null;
var timer_cycle = null;
var time;
var cx=100;
var cy=100;
var radius = Math.random() * 100 % 11 + 10;

var Bubble = function(x, y, col) {
this.col = col;
this.radius = Math.random() * 100 % 11 + 10;
this.wert = Math.ceil(Math.random() * 100 % 10) + 1;
if (x + this.radius > width)
    x -= this.radius;
if (y + this.radius > height)
    y -= this.radius;
if (x - this.radius < 0)
    x += this.radius;
if (y - this.radius < 0)
    y += this.radius;
this.x = x;
this.y = y;
this.diffX = (Math.random() * 19) + 1;
this.diffY = (Math.random() * 19) + 1;
var length = Math.sqrt(this.diffX*this.diffX+this.diffY*this.diffY);
this.diffX = this.diffX / length;
this.diffY = this.diffY / length;

this.speed = Math.random() * 100 % 6 + 3;
}

function hitbubble(x, y, bubble) {
  var dx = Math.abs(x - bubble.x);
  var dy = Math.abs(y - bubble.y);
  var distance = dx*dx+dy*dy;
  if (distance < (bubble.radius*bubble.radius)) {
    alert("getroffen!");
    return bubble;
  } else {
    return null;
    }
}

function Onclick(e) {
  /*alert("Hallo");
  */
  var hit = null;
  var index = -1;
  for (var i = 0; i < BubbleList.length; i++) {
    hit = hitbubble(e.offsetX, e.offsetY, BubbleList[i]);
    if (hit) {
      index = i;
    }
  }
  if (index >= 0) {
    BubbleList.splice(index, 1);


    }

}

function mouseIsInsideCircle(mouseX, mouseY, cx, cy, radius) {
    var dx = mouseX - cx;
    var dy = mouseY - cy;
    return (dx * cx + dy * cy <= radius * radius);
}
//b.x, b.y, b.radius, 0, 2*Math.PI

function getMousePos(zeichenflaeche, evt) {

    var rect = zeichenflaeche.getBoundingClientRect();

    return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
    };

}

zeichenflaeche.addEventListener('mousemove', function (evt) {
    var mousePos = getMousePos(zeichenflaeche, evt);
    var message = 'Mouse position: ' + parseInt(mousePos.x) + ',' + parseInt(mousePos.y);
    writeMessage(zeichenflaeche, message);
}, false);


var mousePos;
function writeMessage(zeichenflaeche, message) {
    ctx.clearRect(0, 10, zeichenflaeche.width, 30);
    ctx.font = '18pt Calibri';
    ctx.fillStyle = 'black';
    ctx.fillText(message, 18, 25);
}

zeichenflaeche.addEventListener('mousedown', function (evt) {
    var mousePos = getMousePos(zeichenflaeche, evt);
    var mouseX = mousePos.x;
    var mouseY = mousePos.y;
    // Unnoetiger Code ausgeklammert
    /*if (mouseIsInsideCircle(mouseX, mouseY, cx, cy, radius)) {

        // erase the canvas
        ctx.clearRect(0, 0, zeichenflaeche.width, zeichenflaeche.height);
    }
    */

}, false);

function init() {
  var points;
  points = 0;
  BubbleList = new Array();
  width = zeichenflaeche.width;
  height = zeichenflaeche.height;
  erzeugeBubbleMenge(10);
  zeichenflaeche.addEventListener("mousedown", Onclick);
  if (!interval_handle)
    interval_handle = setInterval(draw,80);
    alert("Willkommen zu Circlecatch!");
}


function draw() {
   ctx.clearRect(0, 0, width, height);
   ctx.font = "17pt Impact";
   update();
   for (var i = 0; i < BubbleList.length; i++) {
   var b = BubbleList[i];
   ctx.beginPath();
   ctx.fillStyle = b.col;
   ctx.arc(b.x, b.y, b.radius, 0, 2*Math.PI);
   ctx.fill();
   ctx.fillStyle = "#000000";
   ctx.closePath();

   var w = ctx.measureText(b.wert).width;
   var h = parseInt(ctx.font) * 0.5;
    ctx.fillText(b.wert, b.x - w / 3, b.y + h / 3);

   }
   ctx.fillstyle = "#000000";
     var min = time / 1000;
     var time;
     time = null;
     var d = new Date();
     var s = new Date();
     var dK = d.getHours() * 60 * 60 * 1000 + d.getMinutes() * 60 * 1000 + d.getSeconds() * 1000 + d.getMilliseconds();
     var sK = s.getHours() * 60 * 60 * 1000 + s.getMinutes() * 60 * 1000 + s.getSeconds() * 1000 + s.getMilliseconds();
     var dif = (dK-sK) /1000;
     ntime = ((new Date().getTime()/1000)- dif/1000);
     //Bedingung fehlt Falsch,Fehler, mache ich morgen
     ctx.fillText(ntime.toFixed(1) + " Sekunden", 0, height);

}
function update() {
        for (var i = 0; i < BubbleList.length; i++) {
        if (BubbleList[i].x + BubbleList[i].diffX * BubbleList[i].speed + BubbleList[i].radius > width || BubbleList[i].x + BubbleList[i].diffX * BubbleList[i].speed - BubbleList[i].radius < 0) {
     BubbleList[i].diffX *= -1;
}
    if (BubbleList[i].y + BubbleList[i].diffY * BubbleList[i].speed + BubbleList[i].radius > height || BubbleList[i].y + BubbleList[i].diffY * BubbleList[i].speed - BubbleList[i].radius < 0) {
       BubbleList[i].diffY *= -1;
}
     BubbleList[i].x += BubbleList[i].diffX * BubbleList[i].speed;
     BubbleList[i].y += BubbleList[i].diffY * BubbleList[i].speed;
}
}

function erzeugeEinzelneBubble() {
   var x = Math.ceil(Math.random() * width);
   var y = Math.ceil(Math.random() * height);
   var bubble = new Bubble(x, y, "#1BD2D8");
   BubbleList.push(bubble);
}
function erzeugeBubbleMenge(anzahl) {
BubbleList.splice(0, BubbleList.length);
for (var i = 0; i < anzahl; i++) {
     erzeugeEinzelneBubble();
}
}
 
Zuletzt bearbeitet:
Update:
Zeit funktioniert jetzt.

Es wäre schön, wenn mein schieberegler korrekt funktionieren würde.
Der Regler funktioniert zwar, gibt aber nicht den aktuellen Wert aus, d.h.:
HTML:
<div id="einstellungen">
            <input name="anzahl2" type="range" min="9" max="20" value="10" step="1" onchange="showValue(this.value)"/> 
            <span id="range">10</span>
            <br /><br />
            <p>Regler braucht Bugfix.</p>
</div>
Wenn ich showValue(this.value) in erzeugeBubbleMenge(this.value) ändere, dann funktioniert es zwar, aber nur durch zählen weiß ich dass es geht.
Die eigentliche Anzahl wird zu keinem Zeitpunkt ausgegeben.
 
Zuletzt bearbeitet von einem Moderator:
lässt sich das problem evtl. mit weniger code reproduzieren? dann bekommt man meistens eher antwort.
und verwende bitte code tags. hab das schon nachgeholt.
 
Was macht denn die Funktion showValue genau?

Aber onchange ist sowieso nicht ideal, wenn du den Wert des Sliders anzeigen willst.

Code:
<div id="einstellungen">
            <input name="anzahl2" type="range" min="9" max="20" value="10" step="1" onchange="erzeugeBubbleMenge(this.value)" oninput="document.getElementById('range').innerHTML = this.value;"/> 
            <span id="range">10</span>
            <br /><br />
            <p>Regler braucht Bugfix.</p>
</div>
 
Ein Verbesserungsvorschlag um es interessanter zu machen wäre die Anwendung von Physik, die Kugeln sollten aufeinanderprallen und im Eintritts- = Austrittswinkel wieder abprallen, das fänd ich noch prolike ;)
 
Hallo alle miteinander!
hier mal ein Link zur aktuellen Webversion:
Index of /projektbeta

Zeit müsste nun gehen und auch die Punkte!

Das mit der Physik wäre eine Idee!

- - - Aktualisiert - - -

Showvalue ist ein neuer Befehl von HTML5 und damit lassen sich so Schieber leicht programmieren...

Hier die Function:
Code:
function showValue(anzahl2){
    document.getElementById("range").innerHTML=anzahl2;
}

Und da wird eher manipuliert.......
 
Zurück
Oben