doulao2916 2019-04-29 12:18
浏览 59
已采纳

如何使子弹始终以相同的速度向鼠标光标的方向移动?

I got a problem with a game of mine. It is a top down shooter and if I am pressing the mouse a bullet should shoot in the direction of where the mouse was. The problem is that with my attempt the bullet would be faster when the distance between player and mouse is bigger and slower when the distance is smaller. I want that speed to be constant no matter what.

This is what my logic looks like so far:

In the constructor I give the bullet a xDir and a yDir: b.xDir = (float64(mouseX) - b.x) b.yDir = (float64(mouseY) - b.y)

Then in the update function I multiply it with deltaTime and the bullets movementSpeed and add it to the corresponding position axis: b.x += b.movementSpeed * dt * b.xDir b.y += b.movementSpeed * dt * b.yDir

With that logic the bullet speed is depending on the distance between mouse and player. I would appreciate an answer which would not mess with the speed but would still go in the direction of the mouse click.

Thanks in advance :)

  • 写回答

2条回答 默认 最新

  • dongmeng2509 2019-04-29 18:32
    关注

    The problem is that your b.xDir and b.yDir values are directly calculated from the distance, so the farther the mouse click from the player, the higher the values will be. When they are multiplied by dt, it makes them move faster.

    What you need is to normalize your vector, so you only have a direction and not a magnitude carried over from the original click distance. You probably want to use a vector library, but if you're going to do it by scratch, it would look like this:

    magnitude := math.Sqrt(b.XDir * b.xDir + y.xDir * y.xDir)
    b.xDir /= magnitude
    b.yDir /= magnitude
    

    At that point the value of your variables is purely a direction, and multiplying by speed and dt will have the expected effects.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题