खेल आंदोलन
गेम रोटेशन चैप्टर में बताए गए घटकों को खींचने के नए तरीके के साथ, मूवमेंट अधिक लचीले होते हैं।
वस्तुओं को कैसे स्थानांतरित करें?
speed
कंस्ट्रक्टर में एक संपत्ति जोड़ें component
, जो घटक की वर्तमान गति का प्रतिनिधित्व करता है।
और newPos()
के आधार पर, घटक की स्थिति की गणना करने के लिए विधि में कुछ परिवर्तन भी करें ।speed
angle
डिफ़ॉल्ट रूप से, घटकों का सामना करना पड़ रहा है, और गति संपत्ति को 1 पर सेट करके, घटक आगे बढ़ना शुरू कर देगा।
उदाहरण
function component(width, height, color, x, y) {
this.gamearea = gamearea;
this.width = width;
this.height = height;
this.angle = 0;
this.speed = 1;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = color;
ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
ctx.restore();
}
this.newPos = function() {
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
}
मोड़ बनाना
हम भी बाएँ और दाएँ मुड़ने में सक्षम होना चाहते हैं। नामक एक नई संपत्ति बनाएं moveAngle
, जो वर्तमान चलती मूल्य, या रोटेशन कोण को इंगित करता है। newPos()
विधि में संपत्ति के
आधार पर angle
गणना करें:moveAngle
उदाहरण
मूवमेंट प्रॉपर्टी को 1 पर सेट करें और देखें कि क्या होता है:
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.angle = 0;
this.moveAngle = 1;
this.speed = 1;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = color;
ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
ctx.restore();
}
this.newPos = function() {
this.angle += this.moveAngle * Math.PI / 180;
this.x += this.speed * Math.sin(this.angle);
this.y -= this.speed * Math.cos(this.angle);
}
}
कीबोर्ड का प्रयोग करें
कीबोर्ड का उपयोग करते समय लाल वर्ग कैसे चलता है? जब आप "ऊपर" तीर का उपयोग करते हैं, तो ऊपर और नीचे, और एक तरफ से दूसरी ओर जाने के बजाय, लाल वर्ग आगे बढ़ता है, और बाएँ और दाएँ तीरों को दबाने पर बाएँ और दाएँ मुड़ता है।