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 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制