【问题标题】:Animator in c++ with SDL2带有 SDL2 的 C++ 动画师
【发布时间】:2015-03-14 20:09:06
【问题描述】:

我尝试创建一个映射,其中键是枚举,值是 SDL_Rect 数组(其中包含)动画的所有坐标。

std::map<Animation, SDL_Rect*> animations; 
Animation currAnim;

我不想像我找到的解决方案 here 那样定义固定数量的动画。我能怎么做 ?因为

SDL_Rect right[3];
right[0].x = 264;
right[0].y = 0;
right[0].w = 36;
right[0].h = 64;
...
animations.insert(std::pair<Animation, SDL_Rect*>(Animation::MoveRight, right));

没用。

我试过了,但我知道我的绘图中有另一个问题,我必须找到带有 int(帧)的向量元素:

void Player::Draw(SDL_Renderer * renderer, int frame)
{
    std::vector<SDL_Rect>::iterator it = std::find(animator->GetAnimations()[animator->GetCurrAnim()].begin(),
        animator->GetAnimations()[animator->GetCurrAnim()].end(), frame);

    SDL_RenderCopy(renderer, lTexture->GetTexture(), &*it, &rect);
}

我试过了,但是有一个错误说

'==' There is no operator found which accept type "SDL_Rect"

【问题讨论】:

  • 不起作用是什么意思?编译错误(包括错误)、运行时错误(是的,包括错误)等
  • 当您只存储指向其中一个的指针时,为什么要说“SDL_Rect 数组”?即便如此,为什么要使用指针? std::map&lt;Animation, SDL_Rect&gt; 或者如果真的是一个数组 std::map&lt;Animation, std::vector&lt;SDL_Rect&gt;&gt;
  • @LewisBolender there is an exception and the program crashes 好吧,您在我认为不需要它们的地方使用指针。仅此一项就是该程序出现问题的原因之一。可能该数组超出范围,并且地图现在以垃圾数据结束。如果是这种情况,请使用 std::vector&lt;SDL_Rect&gt; 作为地图的键,而不是 SDL_Rect *
  • 这应该说std::vector&lt;SDL_Rect&gt;作为地图中的数据。通过使用SDL_Rect * 作为数据,您将该映射绑定到该数组。如果该数组超出范围,则您的地图具有无效值。此外,请发布更多代码并解释异常发生在哪一行(而不是说“它不起作用”)。除非发布更多代码,否则没有人可以给你一个明确的答案。

标签: c++ arrays dictionary sdl sdl-2


【解决方案1】:

我猜你使用的数组超出了范围,因此你存储在地图中的指针不再有效。

由于您没有发布所有代码,因此给您的一个建议是不要将指针作为数据存储在地图中。相反,请使用std::vector

#include <map>
#include <vector>
typedef std::map<Animation, std::vector<SDL_Rect>> AnimationMap;
//...
AnimationMap animations;
//...
std::vector<SDL_Rect> right(3);
right[0].x = 264;
right[0].y = 0;
right[0].w = 36;
right[0].h = 64;
//...
animations.insert(std::make_pair(Animation::MoveRight, right));
//...

如果矢量right 超出范围,地图仍然可以,因为矢量的副本 被放置在地图的数据部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多