草庐IT

JavaScript 游戏视口(viewport)

coder 2024-12-29 原文

您好,我是 JavaScript 的新手,因此决定按照 w3schools game tutorial 了解更多信息.

我决定让它成为一款平台游戏,但我一直无法弄清楚如何在 Canvas 外添加跟随玩家的视口(viewport)。

谁能帮帮我?提前致谢。

Fiddle

//Background
var Background;

//Objects
var Player;
var Obstacle;

//Mobile buttons
var UpBtn;
var DownBtn;
var LeftBtn;
var RightBtn;
//End

function startGame() {
    Background = new component(656, 270, "gray", 0, 0);

    Player = new component(30, 30, "blue", 200, 75);

    Obstacle = new component(10,100, "red", 300, 170);

  //Mobile buttons
    UpBtn = new component(0, 0, "black", 50, 160);    
    DownBtn = new component(0, 0, "black", 50, 220);    
    LeftBtn = new component(30, 30, "black", 20, 200);    
    RightBtn = new component(30, 30, "black", 90, 200); 
    //End
    myGameArea.start();
}

var myGameArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.interval = setInterval(updateGameArea, 20);
        //Mobile buttons
        window.addEventListener('mousedown', function (e) {
            myGameArea.x = e.pageX;
            myGameArea.y = e.pageY;
        })
        window.addEventListener('mouseup', function (e) {
            myGameArea.x = false;
            myGameArea.y = false;
        })
        window.addEventListener('touchstart', function (e) {
            myGameArea.x = e.pageX;
            myGameArea.y = e.pageY;
        })
        window.addEventListener('touchend', function (e) {
            myGameArea.x = false;
            myGameArea.y = false;
        })
        //End


        //Keyboard
        window.addEventListener('keydown', function (e) {
          myGameArea.keys = (myGameArea.keys || []);
          myGameArea.keys[e.keyCode] = true;
        })
        window.addEventListener('keyup', function (e) {
          myGameArea.keys[e.keyCode] = false; 
        })
        //End

    },
    stop : function() {
        clearInterval(this.interval);
    },    
    clear : function() {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    },
    dead : function() {
      myGameArea.stop();
      startGame();
    }
}

function component(width, height, color, x, y, type) {
    this.type = type;
    if (type == "image") {
    this.image = new Image();
    this.image.src = color;
    }
    this.width = width;
    this.height = height;
    this.x = x;
    this.y = y;
    speed = 4;
    this.speedX = 0;
    this.speedY = 0;    
    this.gravity = 0.175;
    this.gravitySpeed = 0;
    this.bounce = 1;
    this.update = function() {

        ctx = myGameArea.context;
        if (type == "image") {
            ctx.drawImage(this.image, 
                this.x, 
                this.y,
                this.width, this.height);
    } else {
        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.hitBottom();
    }
    this.hitBottom = function() {
        var rockbottom = myGameArea.canvas.height - this.height;
        if (this.y > rockbottom) {
            this.y = rockbottom;
            this.gravitySpeed = -(this.gravitySpeed * this.bounce);
        }
    }
//Mobile buttons
    this.clicked = function() {
        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);
        var clicked = true;
        if ((mybottom < myGameArea.y) || (mytop > myGameArea.y) || (myright < myGameArea.x) || (myleft > myGameArea.x)) {
            clicked = false;
        }
        return clicked;
    }
    //End

      this.crashWith = function(otherobj) {
    var myleft = this.x;
    var myright = this.x + (this.width);
    var mytop = this.y;
    var mybottom = this.y + (this.height);
    var otherleft = otherobj.x;
    var otherright = otherobj.x + (otherobj.width);
    var othertop = otherobj.y;
    var otherbottom = otherobj.y + (otherobj.height);
    var crash = true;
    if ((mybottom < othertop) ||
    (mytop > otherbottom) ||
    (myright < otherleft) ||
    (myleft > otherright)) {
      crash = false;
    }
    return crash;
  }
}

function updateGameArea() {

    if (Player.crashWith(Obstacle)) {
    myGameArea.dead();
  } else {
    myGameArea.clear();
    Obstacle.update();
  }
    //Mobile buttons
        if (myGameArea.x && myGameArea.y) {
        /*if (myUpBtn.clicked()) {
            Player.y -= this.speed;
        }
        if (myDownBtn.clicked()) {
            Player.y += this.speed;
        }*/
        if (LeftBtn.clicked()) {
            Player.x += -this.speed;
        }
        if (RightBtn.clicked()) {
            Player.x += this.speed;
        }
    }
    UpBtn.update();        
    DownBtn.update();        
    LeftBtn.update();     
    RightBtn.update();                                
    Player.update();

    //End

    //Keyboard
  Player.speedX = 0;
  Player.speedY = 0; 

  if (myGameArea.keys && myGameArea.keys[37]) {Player.speedX = -this.speed; }
  if (myGameArea.keys && myGameArea.keys[39]) {Player.speedX = this.speed; }
  //if (myGameArea.keys && myGameArea.keys[38]) {Player.speedY = -this.speed; }
  //if (myGameArea.keys && myGameArea.keys[40]) {Player.speedY = this.speed; }
  //End
    Background.newPos(); 
    Background.update();
    Player.newPos();
    Player.update();

    Obstacle.update();

    //UpBtn.update();        
    //DownBtn.update();        
    LeftBtn.update();     
    RightBtn.update();
}

最佳答案

您可以创建一个变量来存储 Canvas 中的 offsetX:

var offsetX = 0;

然后,在 updateGameArea() 方法中,更新此 offsetX 以玩家 x 坐标为中心:

offsetX = Player.x - myGameArea.canvas.width/2;

另外,绘制组件时减去offsetX:

ctx.fillRect(
    this.x - (this.isFixed ? 0 : offsetX), // <--- here
    this.y, 
    this.width, 
    this.height);

我还创建了一个新属性来判断组件是否固定在屏幕上:

this.isFixed = false;

然后将 isFixed = true 设置为控制按钮和背景:

Background.isFixed=true;
LeftBtn.isFixed=true;
RightBtn.isFixed=true;

这是更新后的代码 (Fiddle):

https://jsfiddle.net/xkbvphjz/13/

完整代码:

//Background
var Background;

//Objects
var Player;
var Obstacle;

//Mobile buttons
var UpBtn;
var DownBtn;
var LeftBtn;
var RightBtn;
//End

var offsetX = 0;

function startGame() {
    Background = new component(656, 270, "gray", 0, 0);
        Background.isFixed=true;

    Player = new component(30, 30, "blue", 200, 75);

    Obstacle = new component(10,100, "red", 300, 170);

  //Mobile buttons
    UpBtn = new component(0, 0, "black", 50, 160);    
    DownBtn = new component(0, 0, "black", 50, 220);    
    LeftBtn = new component(30, 30, "black", 20, 200);
    LeftBtn.isFixed=true;
    RightBtn = new component(30, 30, "black", 90, 200); 
    RightBtn.isFixed=true;
    //End
    myGameArea.start();
}

var myGameArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas, document.body.childNodes[0]);
        this.interval = setInterval(updateGameArea, 20);
        //Mobile buttons
        window.addEventListener('mousedown', function (e) {
            myGameArea.x = e.pageX;
            myGameArea.y = e.pageY;
        })
        window.addEventListener('mouseup', function (e) {
            myGameArea.x = false;
            myGameArea.y = false;
        })
        window.addEventListener('touchstart', function (e) {
            myGameArea.x = e.pageX;
            myGameArea.y = e.pageY;
        })
        window.addEventListener('touchend', function (e) {
            myGameArea.x = false;
            myGameArea.y = false;
        })
        //End


        //Keyboard
        window.addEventListener('keydown', function (e) {
          myGameArea.keys = (myGameArea.keys || []);
          myGameArea.keys[e.keyCode] = true;
        })
        window.addEventListener('keyup', function (e) {
          myGameArea.keys[e.keyCode] = false; 
        })
        //End

    },
    stop : function() {
        clearInterval(this.interval);
    },    
    clear : function() {
        this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    },
    dead : function() {
      myGameArea.stop();
      startGame();
    }
}

function component(width, height, color, x, y, type, isFixed) {
    this.type = type;
    if (type == "image") {
    this.image = new Image();
    this.image.src = color;
    }
    this.width = width;
    this.height = height;
    this.x = x;
    this.y = y;
    speed = 4;
    this.speedX = 0;
    this.speedY = 0;    
    this.gravity = 0.175;
    this.gravitySpeed = 0;
    this.bounce = 1;
    this.isFixed = false;
    this.update = function() {

        ctx = myGameArea.context;
        if (type == "image") {
            ctx.drawImage(this.image, 
                this.x - (this.isFixed ? 0 : offsetX), 
                this.y,
                this.width, this.height);
    } else {
        ctx.fillStyle = color;
        ctx.fillRect(
            this.x - (this.isFixed ? 0 : offsetX),
            this.y, 
          this.width, 
          this.height);
    }
}
    this.newPos = function() {
            if (!this.isFixed) {
          this.gravitySpeed += this.gravity;
          this.x += this.speedX;
          this.y += this.speedY + this.gravitySpeed;
          this.hitBottom();
          //offsetX += this.speedX;
        }
    }
    this.hitBottom = function() {
        var rockbottom = myGameArea.canvas.height - this.height;
        if (this.y > rockbottom) {
            this.y = rockbottom;
            this.gravitySpeed = -(this.gravitySpeed * this.bounce);
        }
    }
//Mobile buttons
    this.clicked = function() {
        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);
        var clicked = true;
        if ((mybottom < myGameArea.y) || (mytop > myGameArea.y) || (myright < myGameArea.x) || (myleft > myGameArea.x)) {
            clicked = false;
        }
        return clicked;
    }
    //End

      this.crashWith = function(otherobj) {
    var myleft = this.x;
    var myright = this.x + (this.width);
    var mytop = this.y;
    var mybottom = this.y + (this.height);
    var otherleft = otherobj.x;
    var otherright = otherobj.x + (otherobj.width);
    var othertop = otherobj.y;
    var otherbottom = otherobj.y + (otherobj.height);
    var crash = true;
    if ((mybottom < othertop) ||
    (mytop > otherbottom) ||
    (myright < otherleft) ||
    (myleft > otherright)) {
      crash = false;
    }
    return crash;
  }
}

function updateGameArea() {

    if (Player.crashWith(Obstacle)) {
    myGameArea.dead();
  } else {
    myGameArea.clear();
    Obstacle.update();
  }
    //Mobile buttons
        if (myGameArea.x && myGameArea.y) {
        /*if (myUpBtn.clicked()) {
            Player.y -= this.speed;
        }
        if (myDownBtn.clicked()) {
            Player.y += this.speed;
        }*/
        if (LeftBtn.clicked()) {
            Player.x += -this.speed;
        }
        if (RightBtn.clicked()) {
            Player.x += this.speed;
        }
    }
    UpBtn.update();        
    DownBtn.update();        
    LeftBtn.update();     
    RightBtn.update();                                
    Player.update();

    offsetX = Player.x - myGameArea.canvas.width/2;

    //End

    //Keyboard
  Player.speedX = 0;
  Player.speedY = 0; 

  if (myGameArea.keys && myGameArea.keys[37]) {Player.speedX = -this.speed; }
  if (myGameArea.keys && myGameArea.keys[39]) {Player.speedX = this.speed; }
  //if (myGameArea.keys && myGameArea.keys[38]) {Player.speedY = -this.speed; }
  //if (myGameArea.keys && myGameArea.keys[40]) {Player.speedY = this.speed; }
  //End
    Background.newPos(); 
    Background.update();
    Player.newPos();
    Player.update();

    Obstacle.update();

    //UpBtn.update();        
    //DownBtn.update();        
    LeftBtn.update();     
    RightBtn.update();
}

关于JavaScript 游戏视口(viewport),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57706710/

有关JavaScript 游戏视口(viewport)的更多相关文章

  1. ruby - 我需要从 facebook 游戏中抓取数据——使用 ruby - 2

    修改(澄清问题)我已经花了几天时间试图弄清楚如何从Facebook游戏中抓取特定信息;但是,我遇到了一堵又一堵砖墙。据我所知,主要问题如下。我可以使用Chrome的检查元素工具手动查找我需要的html-它似乎位于iframe中。但是,当我尝试抓取该iframe时,它​​是空的(属性除外):如果我使用浏览器的“查看页面源代码”工具,这与我看到的输出相同。我不明白为什么我看不到iframe中的数据。答案不是它是由AJAX之后添加的。(我知道这既是因为“查看页面源代码”可以读取Ajax添加的数据,也是因为我有b/c我一直等到我可以看到数据页面之后才抓取它,但它仍然不存在)。发生这种情况是因为

  2. ruby-on-rails - 使用 javascript 更改数据方法不会更改 ajax 调用用户的什么方法? - 2

    我遇到了一个非常奇怪的问题,我很难解决。在我看来,我有一个与data-remote="true"和data-method="delete"的链接。当我单击该链接时,我可以看到对我的Rails服务器的DELETE请求。返回的JS代码会更改此链接的属性,其中包括href和data-method。再次单击此链接后,我的服务器收到了对新href的请求,但使用的是旧的data-method,即使我已将其从DELETE到POST(它仍然发送一个DELETE请求)。但是,如果我刷新页面,HTML与"new"HTML相同(随返回的JS发生变化),但它实际上发送了正确的请求类型。这就是这个问题令我困惑的

  3. python - Ruby 或 Python 的 3d 游戏引擎? - 2

    关闭。这个问题不符合StackOverflowguidelines.它目前不接受答案。要求我们推荐或查找工具、库或最喜欢的场外资源的问题对于StackOverflow来说是偏离主题的,因为它们往往会吸引自以为是的答案和垃圾邮件。相反,describetheproblem以及迄今为止为解决该问题所做的工作。关闭9年前。Improvethisquestion是否有适用于这些的3d游戏引擎?

  4. ruby - 在 Mechanize 中使用 JavaScript 单击链接 - 2

    我有这个:AccountSummary我想单击该链接,但在使用link_to时出现错误。我试过:bot.click(page.link_with(:href=>/menu_home/))bot.click(page.link_with(:class=>'top_level_active'))bot.click(page.link_with(:href=>/AccountSummary/))我得到的错误是:NoMethodError:nil:NilClass的未定义方法“[]” 最佳答案 那是一个javascript链接。Mechan

  5. javascript - jQuery 的 jquery-1.10.2.min.map 正在触发 404(未找到) - 2

    我看到有关未找到文件min.map的错误消息:GETjQuery'sjquery-1.10.2.min.mapistriggeringa404(NotFound)截图这是从哪里来的? 最佳答案 如果ChromeDevTools报告.map文件的404(可能是jquery-1.10.2.min.map、jquery.min.map或jquery-2.0.3.min.map,但任何事情都可能发生)首先要知道的是,这仅在使用DevTools时才会请求。您的用户不会遇到此404。现在您可以修复此问题或禁用sourcemap功能。修复:获取文

  6. ruby-on-rails - 我将 Rails3 与 tinymce 一起使用。如何呈现用户关闭浏览器javascript然后输入xss? - 2

    我有一个用Rails3编写的站点。我的帖子模型有一个名为“内容”的文本列。在帖子面板中,html表单使用tinymce将“content”列设置为textarea字段。在首页,因为使用了tinymce,post.html.erb的代码需要用这样的原始方法来实现。.好的,现在如果我关闭浏览器javascript,这个文本区域可以在没有tinymce的情况下输入,也许用户会输入任何xss,比如alert('xss');.我的前台会显示那个警告框。我尝试sanitize(@post.content)在posts_controller中,但sanitize方法将相互过滤tinymce样式。例如

  7. ruby - 使用 Selenium WebDriver 启用/禁用 javascript - 2

    出于某种原因,我必须为Firefox禁用javascript(手动,我们按照提到的步骤执行http://support.mozilla.org/en-US/kb/javascript-settings-for-interactive-web-pages#w_enabling-and-disabling-javascript)。使用Ruby的SeleniumWebDriver如何实现这一点? 最佳答案 是的,这是可能的。而是另一种方式。您首先需要查看链接Selenium::WebDriver::Firefox::Profile#[]=

  8. ruby - Watir-Webdriver 是否支持点击目标为 javascript 的链接? - 2

    我是Ruby和Watir-Webdriver的新手。我有一套用VBScript编写的站点自动化程序,我想将其转换为Ruby/Watir,因为我现在必须支持Firefox。我发现我真的很喜欢Ruby,而且我正在研究Watir,但我已经花了一周时间试图让Webdriver显示我的登录屏幕。该站点以带有“我同意”区域的“警告屏幕”开头。用户点击我同意并显示登录屏幕。我需要单击该区域以显示登录屏幕(这是同一页面,实际上是一个表单,只是隐藏了)。我整天都在用VBScript这样做:objExplorer.Document.GetElementsByTagName("area")(0).click

  9. ruby - 使用 Ruby 编写 Unity 游戏 - 2

    所以我看到unity支持c#、JS和Boo。我可以学习其中一个,但我想制作一个“编译器”或类似的东西,让我可以编写ruby​​代码并输出JS代码或制作一个可以被Unity编译器读取的层。这有可能吗?我愿意在这方面投入很多时间并且有相当多的经验。 最佳答案 如果您的问题实际上是“我如何将Ruby编译为JavaScript”,那么这更容易回答:Opal:RubytoJavaScriptcompiler但是,学习其中一种受支持的语言会更好。当运行的是用另一种语言解释的代码时,很难调试“您的”代码。

  10. 网页设计期末作业,基于HTML+CSS+JavaScript超酷超炫的汽车类企业网站(6页) - 2

    🎉精彩专栏推荐💭文末获取联系✍️作者简介:一个热爱把逻辑思维转变为代码的技术博主💂作者主页:【主页——🚀获取更多优质源码】🎓web前端期末大作业:【📚毕设项目精品实战案例(1000套)】🧡程序员有趣的告白方式:【💌HTML七夕情人节表白网页制作(110套)】🌎超炫酷的Echarts大屏可视化源码:【🔰Echarts大屏展示大数据平台可视化(150套)】🔖HTML+CSS+JS实例代码:【🗂️5000套HTML+CSS+JS实例代码(炫酷代码)继续更新中…】🎁免费且实用的WEB前端学习指南:【📂web前端零基础到高级学习视频教程120G干货分享】🥇关于作者:💬历任研发工程师,技术组长,教学总监;

随机推荐