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 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。