What Am I not doing correctly? Collision with Pythagorean

Creature.cs

using System;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace Project1
{
public class Creature : DrawableGameComponent
{

    protected cState creatureState;  // state
    protected Texture2D humanTexture;
    protected Texture2D zombieTexture;
    protected Rectangle drawRect;
    protected SpriteBatch spriteBatch;

    protected Vector2 Position;
    protected Vector2 Direction;

    protected float speed;
    protected int dFrame;  // frames since new direction
    protected int framesPerDir;  // number of frames to spend in each direction

    protected Game1 game;
    protected Random rand;
    protected float screenWidth;
    protected float screenHeight;
    
   


    float collideDistance = 2;
    
    

    public cState getState()
    {

        return creatureState;
    
    }

    public void setState(cState ia)
    {
        creatureState = ia;
    }

    public bool collides(Creature other)
    {
        //If ( ((ax-bx)*(ax-bx) + (ay-by)*(ay-by)) < collideDistance2) then collide = true;
        if (((humanTexture.Height - zombieTexture.Height) * (humanTexture.Height - zombieTexture.Height) +
            (humanTexture.Width - zombieTexture.Width) * (humanTexture.Width - zombieTexture.Width)) < collideDistance * collideDistance)
            return false;
        else
        return true;

    }

    public Creature(Game1 theGame, float ix, float iy, cState state)
        : base(theGame)
    {
        Position = new Vector2(ix, iy);

        Direction = new Vector2();

        creatureState = state;

        game = theGame;
    }


    public override void Initialize()
    {
        base.Initialize();
    }


    protected override void LoadContent()
    {
        speed = 6.5f;  // set to your speed
        dFrame = 0;
        framesPerDir = 60;  // set to your frames Per Direction
        rand = game.getRand();

        Direction.Y = (float)rand.NextDouble() - 0.5f;
        Direction.X = (float)rand.NextDouble() - 0.5f;

        Position.Y = rand.Next(0, 700);
        Position.X = rand.Next(100, 800);


        spriteBatch = game.getSpriteBatch();
        screenWidth = game.getScreenWidth();
        screenHeight = game.getScreenHeight();

        humanTexture = game.getHumanTexture();
        zombieTexture = game.getZombieTexture();


        drawRect = new Rectangle((int)Position.X, (int)Position.Y, humanTexture.Width - 25, humanTexture.Height - 25); // change to adj. sprite size

        base.LoadContent();
    }

    public void kill()
    {
        creatureState = cState.Dead; 
    }

    public Vector2 getPosition()
    {
        return Position;
    }

    public override void Update(GameTime gameTime)
    {
        if (creatureState == cState.Dead) return;

        // add code here to move your sprite
        Position += Direction * speed;

        if (Position.Y > screenHeight-60)
        {
            Direction.Y *= -1.0f;
        }
        if (Position.X > screenWidth-60)
        {
            Direction.X *= -1.0f;
        }
        if (Position.X < 0)
        {
            Direction.X *= -1.0f;
        }
        if (Position.Y < 0)
        {
            Direction.Y *= -1.0f;
        }


       
        drawRect.X = (int)Position.X;
        drawRect.Y = (int)Position.Y;
    }

    

    public override void Draw(GameTime gameTime)
    {


        switch (creatureState)
        {
            case cState.Dead:
                return; // don't draw anything.

            case cState.Alive:
                spriteBatch.Draw(humanTexture, drawRect, Color.White);
                break;

            case cState.Zombie:
                spriteBatch.Draw(zombieTexture, drawRect, Color.White);
                break;
        }

    }
}

}

Game.cs
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
//using Microsoft.Xna.Framework.Storage;
using System.Diagnostics;//to access Debug

namespace Project1
{
public enum cState { Dead, Alive, Zombie };

public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    public SpriteBatch spriteBatch;
    SpriteFont Font1;
    // in the pipeline program, right click on Content, select add new item
    // and select SpriteFont Description.  And then save.
    //
    //   see http://msdn.microsoft.com/en-us/library/bb447673.aspx
    //   for more details

    int maxThings;  // number of creatures

    Color bgColor;
    float screenWidth, screenHeight;
    Random rand;
    Creature[] thingArray; // creature array

    protected Texture2D humanTexture;
    protected Texture2D zombieTexture;
    

    long elapsedTime;
    double eTime;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";

        graphics.IsFullScreen = false;
        graphics.PreferredBackBufferHeight = 800;
        graphics.PreferredBackBufferWidth = 1600;
        IsFixedTimeStep = false;

        // create new random number generator
        rand = new Random((int)DateTime.Now.Ticks);

    }

    protected override void Initialize()
    {

        //Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);
        screenWidth = (float)(Window.ClientBounds.Width);
        screenHeight = (float)(Window.ClientBounds.Height);

        bgColor = new Color (0,0,0); // set to your background color


        maxThings = 100;  // set number of things
        thingArray = new Creature[maxThings];
        int numThings = 0;

        // create one Human

        { 
            thingArray[numThings] = new Creature(this, 100.0f, 100.0f, cState.Alive);
            Components.Add(thingArray[numThings++]); 
        }

        // create one Zombie 
       
   
            thingArray[numThings] = new Creature(this, 200.0f, 100.0f, cState.Zombie);
            Components.Add(thingArray[numThings++]);
      

        while (numThings < maxThings)
        {  // and a bunch of dead ones
            thingArray[numThings] = new Creature(this, rand.Next(0,(int)screenWidth - 30), rand.Next(0, (int)screenHeight - 30), cState.Alive);
            Components.Add(thingArray[numThings++]);
        }


        // load text font
        Font1 = Content.Load<SpriteFont>("NewSpriteFont");


        humanTexture = Content.Load<Texture2D>("images/Rrr2_cat");
        zombieTexture = Content.Load<Texture2D>("images/Rrr3_cat");

        Debug.WriteLine("Texture Width " + humanTexture.Width);
        Debug.WriteLine("Texture Height " + humanTexture.Height);


        //Debug code for illustration purposes.
        Debug.WriteLine("Window Width " + Window.ClientBounds.Width);
        Debug.WriteLine("Window Height " + Window.ClientBounds.Height);
        Debug.WriteLine("IsFixedTimeStep " + IsFixedTimeStep);
        Debug.WriteLine("TargetElapsedTime " + TargetElapsedTime);
      
        base.Initialize();
    }


    protected override void LoadContent()
    {
        
    }

   

    protected override void UnloadContent()
    {
        //No unload code needed.
    }

    protected override void Update(GameTime gameTime)
    {
        for (int thisThing = 0; thisThing < maxThings; thisThing++)
        {
            if (thingArray[thisThing].getState() == cState.Zombie)
            {

                for (int otherThing = 0; otherThing < maxThings; otherThing++)
                {
                    if (thingArray[otherThing].getState() == cState.Alive)
                    {
                        if (thingArray[otherThing].collides(thingArray[thisThing]))
                        {
                            thingArray[otherThing].setState(cState.Zombie);
                        }
                    }
                }
            }
        }
        // get elapsed time in seconds
        elapsedTime = gameTime.ElapsedGameTime.Ticks;
        eTime = (double)elapsedTime / (double)TimeSpan.TicksPerSecond;

        GetInput(gameTime);  // get user input

        //The following statement is always required.
        base.Update(gameTime);

        KeyboardState keyboardState = Keyboard.GetState();
        if (keyboardState.IsKeyDown(Keys.Escape))
        {
            this.Exit();
        }
    }


    protected void GetInput(GameTime gameTime)
    {
        KeyboardState keyboardState = Keyboard.GetState();
        if (keyboardState.IsKeyDown(Keys.Escape))
        { // id escape key pressed, then exit
            this.Exit();
        }
    }


    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(bgColor);

        spriteBatch.Begin();

        base.Draw(gameTime);  // draw everything else in the game
        
        double fps = 1.0 / eTime;  // calculate and display frame rate
        spriteBatch.DrawString(Font1, "fps " + fps.ToString("f6"), new Vector2(10, 10), Color.White);

        spriteBatch.End();

    }

    public float getScreenWidth()
    {
        return screenWidth;
    }

    public float getScreenHeight()
    {
        return screenHeight;
    }

    public Random getRand()
    {
        return rand;
    }

    public SpriteBatch getSpriteBatch()
    {
        return spriteBatch;
    }

    public Texture2D getHumanTexture()
    {
        return humanTexture;
    }

    public Texture2D getZombieTexture()
    {
        return zombieTexture;
    }




}//End class

}//End namespace

And now go ahead and ask your question properly. What exactly you are expecting and what exactly doesn’t work.

From what I can gather from a quick scan, your intent seems to be to check if the distance between creatures is less than your preset collision distance, but you’re using the width/height of the creature instead of the position.

Maybe take a look at what you mean to do here and what data you’re using to accomplish it :slight_smile:

1 Like