gpt4 book ai didi

c# - Sprite 旋转 XNA

转载 作者:太空宇宙 更新时间:2023-11-03 22:02:52 25 4
gpt4 key购买 nike

我正在尝试通过使用转弯半径递增和递减 Rotation 来旋转 Sprite 以面向鼠标。它可以正常工作,直到鼠标位于左上角并移动到右上角为止。我有它,如果角度差大于当前旋转值,则 Sprite 的旋转会增加,否则会减少。所以当它从 6.5 弧度变为 0 时,它会逆时针旋转 350 度,而不是顺时针旋转 15 度。我和其他人整天都在为此工作,不知道如何解决这个问题。我的代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System.IO;

namespace Physics
{
public class Ship
{
public Texture2D Texture { get; set; }
public Vector2 Position { get; set; }
public double Rotation { get; set; }
MouseState prevState, currState;

Vector2 A, B;

public const double NINETY_DEGREES = 1.57079633;

double turningRadius = 2 * (Math.PI / 180);
double targetRotation, rotationDifferential;

public Ship(Texture2D texture, Vector2 position)
{
Texture = texture;
Position = position;
A = new Vector2(Position.X, Position.Y);
B = new Vector2(Mouse.GetState().X, Mouse.GetState().Y);
Rotation = 0;
}

public void Update()
{
currState = Mouse.GetState();
A.X = Position.X;
A.Y = Position.Y;
B.X = currState.X;
B.Y = currState.Y;

if (B.Y > A.Y)
if (B.X > A.X) //Bottom-right
targetRotation = Math.Atan((B.Y - A.Y) / (B.X - A.X)) + NINETY_DEGREES;
else //Bottom-left
targetRotation = (Math.Atan((A.X - B.X) / (B.Y - A.Y))) + (NINETY_DEGREES * 2);
else
if (B.X > A.X) //Top-right
targetRotation = Math.Atan((B.X - A.X) / (A.Y - B.Y));
else //Top-Left
targetRotation = Math.Atan((A.Y - B.Y) / (A.X - B.X)) + (NINETY_DEGREES * 3);

if (Rotation > targetRotation)
Rotation -= turningRadius;
else
Rotation += turningRadius;

prevState = currState;
}

public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Texture, Position, null, Color.White, (float)Rotation, new Vector2(Texture.Width / 2, Texture.Height / 2), 0.5f,
SpriteEffects.None, 0.0f);
}
}

最佳答案

让我确保我理解。你有一个向量 (Cos(Rotation), Sin(Rotation) 表示你的对象面向哪个方向;另一个向量 (B.X-A.X, B.Y-A.Y) 表示方向你想要你的物体面对;你想知道是顺时针还是逆时针旋转你的物体(第一个向量)以面对它第二个向量的方向?

很简单,只需将它们都视为 3D 向量(设置 Z = 0)并取其 cross product .

  • 如果生成的向量具有正 Z 分量,则逆时针旋转
  • 如果它有一个正的Z分量,顺时针旋转
  • 如果 Z 分量为 0,则两个向量平行,因此只需检查它们是面向相反的方向 (并向任一方向旋转) 还是相同的方向 < em>(无事可做!)

之所以有效,是因为 right-hand rule它定义了叉积。

关于c# - Sprite 旋转 XNA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9526837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com