我不明白BEVY的旋转是怎么运作的.我只想旋转一个精灵来跟随我的光标位置.

有没有人能给我一段让它工作的代码?

我试过了,但没用: Bevy rotation in 2d

use bevy::math::{Quat, Vec2};

let pos = transform.translation.truncate(); // player position
let target = event.position;                // cursor position

let angle = (target - pos).angle_between(pos); // NaN
transform.rotation = Quat::from_rotation_z(angle);

在上面做一个Angular =NaN,所以它不工作.

let pos = transform.translation.truncate(); // player position
let target = cursor_position; // cursor position
            
let direction = target - pos;
let angle = direction.y.atan2(direction.x); // Calculate angle between direction and x-axis
transform.rotation = Quat::from_rotation_z(angle);

结果如下:

enter image description here

这是回购,如果你想试试的话:https://github.com/theocerutti/SpaceGameRust

谢谢!

推荐答案

所需要的是将球员的前部朝向光标旋转.为了做到这一点,还需要描述球员前面的方向的矢量.

angle = (target - pos).angle_between(pos)没有帮助,因为pos没有描述玩家的方位.pos只是玩家的位置.

找到矢量target-pos相对于x轴的Angular 是有用的,但还不够.

从这个Angular ,球员的方向相对于x轴的Angular 应该减go .这将提供所需的旋转Angular .球员应该根据产生的Angular ,围绕通过球员的z轴旋转.

一种解决方案是有一个单独的变量来跟踪对象的方向.该变量必须在每次对象旋转时更新.

use bevy::math::{Quat, Vec2};
use std::f32::consts::PI;

// Initialize player orientation at the very beginning.
// It is the angle with respect to X-axis.
// IMPORTANT NOTE: Check what value it is (0 degrees or 90 degrees etc)
// and set it here.
let player_orient = PI/2.0;

...

let pos = transform.translation.truncate(); // player position
let target = Vec2::new(cursor_position.x - window.width() / 2., cursor_position.y - window.height() / 2.);                // cursor position
let direction = target - pos; 

// obtain angle to target with respect to x-axis. 
let mut angle_to_target = direction.y.atan2(direction.x);
// represent angle_to_target in [0, 2*PI)
if angle_to_target < 0. {
  angle_to_target += 2.0*PI;
}

let angle_to_rotate = angle_to_target - player_orient;
transform.rotation = Quat::from_rotation_z(angle_to_rotate);

// Update the player's orientation.
// Always, represent it in the range [0, 2*PI).
player_orient = (player_orient + angle_to_rotate) % (2.0*PI);

Rust相关问答推荐

如何初始化match声明中的两个变量而不会激怒borrow 判断器?

在‘await’点上使用‘std::同步::Mutex’是否总是会导致僵局?

如何从使用mockall模拟的方法中返回self?

文档示例需要导入相关的 struct ,但仅在运行测试时.这是故意的行为吗?

为什么实例方法可以像Rust中的静态方法一样被调用?

为什么这是&q;,而让&q;循环是无限循环?

在Rust中克隆源自INTO_ITER()的迭代器的成本?

为什么rustc会自动降级其版本?

如何设置activx websocket actorless的消息大小限制?

为什么在 Allocator API 中 allocate() 使用 `[u8]` 而 deallocate 使用 `u8` ?

我可以禁用发布模式的开发依赖功能吗?

Rust: 目标成员属于哪个"目标家族"的列表是否存在?

为什么这段 Rust 代码会在没有递归或循环的情况下导致堆栈溢出?

Rust 中 Mutex<> 的深拷贝?

Rust:`sort_by` 多个条件,冗长的模式匹配

一个函数调用会产生双重borrow 错误,而另一个则不会

如何使返回 XMLError 的方法与 anyhow::Error 兼容?

发生移动是因为 `data` 的类型为 `Vec`,它没有实现 `Copy` 特性

从函数返回 u32 的数组/切片

匹配结果时的简洁日志(log)记录