गेम ग्रेविटी
कुछ खेलों में ऐसी ताकतें होती हैं जो खेल के घटक को एक दिशा में खींचती हैं, जैसे गुरुत्वाकर्षण वस्तुओं को जमीन पर खींचता है।
गुरुत्वाकर्षण
हमारे कंपोनेंट कंस्ट्रक्टर में इस फंक्शनलिटी को जोड़ने के लिए, पहले एक gravity
प्रॉपर्टी जोड़ें, जो करंट ग्रेविटी को सेट करती है। फिर एक gravitySpeed
संपत्ति जोड़ें, जो हर बार जब हम फ्रेम को अपडेट करते हैं तो बढ़ जाती है:
उदाहरण
function component(width, height, color, x, y, type) {
this.type = type;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.speedX = 0;
this.speedY = 0;
this.gravity = 0.05;
this.gravitySpeed = 0;
this.update = function() {
ctx = myGameArea.context;
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
}
}
नीचे मारो
लाल वर्ग को हमेशा के लिए गिरने से रोकने के लिए, खेल क्षेत्र के निचले भाग से टकराने पर गिरना बंद करें:
उदाहरण
this.newPos = function() {
this.gravitySpeed += this.gravity;
this.x += this.speedX;
this.y += this.speedY + this.gravitySpeed;
this.hitBottom();
}
this.hitBottom = function() {
var rockbottom = myGameArea.canvas.height - this.height;
if (this.y > rockbottom) {
this.y = rockbottom;
}
}
तेज करें
एक खेल में, जब आपके पास एक बल होता है जो आपको नीचे खींचता है, तो आपके पास घटक को तेज करने के लिए मजबूर करने का एक तरीका होना चाहिए।
जब कोई बटन क्लिक करता है तो एक फ़ंक्शन ट्रिगर करें, और लाल वर्ग को हवा में ऊपर उठाएं:
उदाहरण
<script>function accelerate(n) {
myGamePiece.gravity = n;
}</script>
<button onmousedown="accelerate(-0.2)" onmouseup="accelerate(0.1)">ACCELERATE</button>
एक खेल
हमने अब तक जो सीखा है, उसके आधार पर एक गेम बनाएं: