引发奇怪的异常:在SFML中获取子画面图像的高度

如何解决引发奇怪的异常:在SFML中获取子画面图像的高度

|| 嗨,所以我已经找到了异常的根,它位于以下代码行:
>= obj2->GetPosition().y + (obj2->GetCenter().y - obj2->GetImage()->GetHeight()))
但是我不知道是什么原因引起的.....函数中的奇怪部分是,它需要两个精灵指针,函数GetImage()-> GetHeight()对对象1有效,但对对象第二次不起作用2 ... 请帮忙!我不知道为什么会这样!谢谢 所有代码:(搜索我之前发布的代码行)
#include<SFML/Graphics.hpp>
#include<SFML/System.hpp>
#include<cmath>
#include<vector>
#    define M_PI 3.14159265358979323846 
enum{xXx= 0,yYy= 1};
enum{ScreenWidth=800,ScreenHeight=600};

sf::RenderWindow Window;

template<typename T/*,typename T2*/>
bool CheckCollision(T* obj1,T* obj2){ 
    bool xColl=false,yColl=false;
    // check if any part of object 1 is between object 2\'s top and bottom 
    if(obj1->GetPosition().y + (obj1->GetCenter().y - obj1->GetImage()->GetHeight())
    <= obj2->GetPosition().y + (obj2->GetImage()->GetHeight() - obj2->GetCenter().y)

    && obj1->GetPosition().y + (obj1->GetImage()->GetHeight() - obj1->GetCenter().y)
    >= obj2->GetPosition().y + (obj2->GetCenter().y - obj2->GetImage()->GetHeight()))
        yColl= true;
    // check if any part of object 1 is between object 2\'s left and right
    if(obj1->GetPosition().x + (obj1->GetCenter().x - obj1->GetImage()->GetWidth())
    <= obj2->GetPosition().x + (obj2->GetImage()->GetWidth() - obj2->GetCenter().x)

    && obj1->GetPosition().x + (obj1->GetImage()->GetWidth() - obj1->GetCenter().x)
    >= obj2->GetPosition().x + (obj2->GetCenter().x - obj2->GetImage()->GetWidth()))
        xColl= true;

    if(xColl==true && yColl==true) return true;
    else return false;
};


template<typename T> 
void CalculateMove(T Time,T Speed,T Angle,T& buffX,T& buffY)
{   //Make the degrees positive
    if(Angle<0) Angle= 360+Angle;

    //determine what quadrant of circle we\'re in     
    unsigned int   Quadrant= 1;     
    if(Angle>=90)  Quadrant= 2;     
    if(Angle>=180) Quadrant= 3;    
    if(Angle>=270) Quadrant= 4;

    //anything above 90 would be impossible triangle
    Angle= (float)(Angle-(int)Angle)+(float)((int)Angle%90); 

    // calculates x and y based on angle and Hypotenuse
    if((int)Angle!=0){
        if(Quadrant==2 || Quadrant==4) Angle=90-Angle; //The unit circle triangle is flipped otherwise,causing x and y to be switched
        buffY= sin(Angle / 180 * M_PI)/ (1.f/(Speed*Time));  
        buffX= sin((180-Angle-90)/ 180 * M_PI)/ (1.f/(Speed*Time));}

    else{// Movement is a straight line on X or Y axis
        if(Quadrant==1 || Quadrant==3) buffX= Speed*Time;
        if(Quadrant==2 || Quadrant==4) buffY= Speed*Time;}

    //Quadrant Factor (positive or negative movement on the axis)
    switch(Quadrant){
    case 1: break;
    case 2: buffX=-buffX; break;
    case 3: buffX=-buffX; buffY=-buffY; break;
    case 4: buffY=-buffY; break;}
};

template<typename T>
struct MoveData{
    float X,Y;
    T* Object;
    MoveData(float x,float y,T* object):X(x),Y(y),Object(object){};
};

/////////////////////////////////////////   Mysprite    ////////////////////////////////
class mySprite : public sf::Sprite
{
private:
    float velocity;
    float angle;

public:
    // all the values needed by the base class sprite();
    mySprite(
        const sf::Image& Img,const sf::Vector2f& Position = sf::Vector2f(0,0),const sf::Vector2f& Scale = sf::Vector2f(1,1),float Rotation = 0.f,const float Angle= 0.f,const float Velocity= 0.f,const sf::Color& Col = sf::Color(255,255,255)):
      Sprite(Img,Position,Scale,Rotation,Col){
        angle= Angle;
        velocity= Velocity;};

    float Velocity(){return velocity;};
    void SetVelocity(float newVelocity){velocity=newVelocity;};
    float Angle(){return angle;};
    void SetAngle(float newAngle){angle=(float)(newAngle-(int)newAngle)+(float)((int)newAngle%360);};

    void Update(){ 
        float frameTime= Window.GetFrameTime();
        float X=0,Y=0;
        //SetRotation(angle);
        CalculateMove(frameTime,velocity,angle,X,Y);
        Move(X,-Y);
    };

    void Accelerate(float PPS){velocity+=PPS;};
    void Turn(float degrees){
        angle=(float)((angle+degrees)-(int)(angle+degrees))+(float)((int)(angle+degrees)%360);};

    void Reflect(float CollAngle){
        SetRotation(-GetRotation());
        angle=360-angle;
        //TODO: factor in the collision angle
    };
};

class MoveBuff
{
private:
    std::vector<MoveData<mySprite>> buff;

public:
    void AddMove(mySprite obj,float X,float Y){
        MoveData<mySprite> data(X,Y,&obj);
        buff.push_back(data);};

    void TestColl(){
        for(unsigned int Object= 0; Object< buff.size(); Object++){
            for(unsigned int CollCheck=Object+1; CollCheck<=buff.size()-1; CollCheck++){    
                if(CheckCollision(buff[Object].Object,buff[CollCheck].Object)){
                    buff[Object].Object->Reflect(0);
                    buff[Object].Object->Reflect(0);}}}
    };

    void Move(){
        for(unsigned int I= 0; I<buff.size(); I++)
            buff[I].Object->Move(buff[I].X,buff[I].Y);
    };
};

int main()
{
    Window.Create(sf::VideoMode(ScreenWidth,ScreenHeight),\"Pong! by Griffin Howlett\",sf::Style::Resize | sf::Style::Close);

    sf::Image img;
    img.Create(30,50,sf::Color(255,0));
    mySprite box(img,sf::Vector2f(400,sf::Vector2f(1,270,100); //TODO: test collision with different speeds
    box.SetCenter(15,25);

    sf::Image img2;
    img2.Create(56.5,80,0));
    mySprite box2(img2,400),90,100);
    box2.SetCenter(25,40);

    Window.Display();

    for(;;){
        Window.Clear();
        MoveBuff MoveBuff;
        float frameTime= Window.GetFrameTime();
        float X=0,Y=0;

        CalculateMove(frameTime,box.Velocity(),box.Angle(),Y);
        MoveBuff.AddMove(box,Y);

        CalculateMove(frameTime,box2.Velocity(),box2.Angle(),Y);
        MoveBuff.AddMove(box2,Y);

        MoveBuff.TestColl();
        MoveBuff.Move();

        Window.Draw(box);
        Window.Draw(box2);
        Window.Display();
    }
}
    

解决方法

        
MoveData(float x,float y,T* object):X(x),Y(y),Object(object){}; // Constructor
                                                // ^^^^^^^^^^^^
                              //  Just making a reference to the argument. Shallow copy.



void AddMove(mySprite obj,float X,float Y){

    MoveData<mySprite> data(X,Y,&obj);
    buff.push_back(data);

}// => lifetime of the obj ends at this point.
构造函数正在制作浅表副本。在初始化器列表中,您只是在引用该参数。但是
obj
的寿命在调用ѭ4call后结束。因此,
MoveData::Object
晃来晃去。取消引用是导致您异常的原因。而是进行深拷贝。
void TestColl()
{
    for(unsigned int Object= 0; Object< buff.size(); Object++){
        for(unsigned int CollCheck=Object+1; CollCheck<=buff.size()-1; CollCheck++){    
             if(CheckCollision(buff[Object].Object,buff[CollCheck].Object)){
                // ^^^^^^^^^ This the problem. buff[Object].Object is dangling.
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res