如何检测与精灵动画的碰撞?
SpriteManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using System.IO;
namespace Mini
{
public class SpriteManager
{
protected Texture2D Texture;
public Vector2 Position = Vector2.Zero;
protected Dictionary<string, AnimationClass> Animations =
new Dictionary<string, AnimationClass>();
protected int FrameIndex = 0;
protected Vector2 Origin;
private int height;
private int width;
private string animation;
public string Animation
{
get { return animation; }
set
{
animation = value;
FrameIndex = 0;
}
}
public int Height
{
get { return height; }
}
public int Width
{
get { return width; }
}
public Rectangle Rectangle
{
get { return Animations[Animation].Rectangles[FrameIndex]; }
}
public Texture2D Texture2D
{
get { return Texture; }
}
public SpriteManager(Texture2D Texture, int Frames, int animations)
{
this.Texture = Texture;
width = Texture.Width / Frames;
height = Texture.Height / animations;
Origin = new Vector2(width / 2, height / 2);
}
public void AddAnimation(string name, int row,
int frames, AnimationClass animation)
{
Rectangle[] recs = new Rectangle[frames];
Color[][] frameImageData = new Color[frames][];
Texture2D[][] frameImage = new Texture2D[frames][];
for (int i = 0; i < frames; i++)
{
recs[i] = new Rectangle(i * width,
(row - 1) * height, width, height);
frameImageData[i] = new Color[width * height];
}
animation.Frames = frames;
animation.Rectangles = recs;
Animations.Add(name, animation);
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(Texture, Position,
Animations[Animation].Rectangles[FrameIndex],
Animations[Animation].Color,
Animations[Animation].Rotation, Origin,
Animations[Animation].Scale,
Animations[Animation].SpriteEffect, 0f);
}
public bool IntersectPixels(SpriteManager b)
{
Rectangle rectangleA = this.Rectangle;
Rectangle rectangleB = b.Rectangle;
int top = Math.Max(rectangleA.Top, rectangleB.Top);
int bottom = Math.Min(rectangleA.Bottom, rectangleB.Bottom);
int left = Math.Max(rectangleA.Left, rectangleB.Left);
int right = Math.Min(rectangleA.Right, rectangleB.Right);
Color[] dataA = new Color[rectangleA.Width * rectangleA.Height];
this.Texture.GetData(0, rectangleA, dataA, 0, rectangleA.Width * rectangleA.Height);
Color[] dataB = new Color[rectangleB.Width * rectangleB.Height];
b.Texture.GetData(0, rectangleB, dataB, 0, b.Width * b.Height);
Stream s = File.Create("t.png");
b.Texture2D.SaveAsPng(s, rectangleB.Width, rectangleB.Height);
for (int y = top; y < bottom; y++)
{
for (int x = left; x < right; x++)
{
Color colorA = dataA[(x - rectangleA.Left) + (y - rectangleA.Top) * rectangleA.Width];
Color colorB = dataB[(x - rectangleB.Left) + (y - rectangleB.Top) * rectangleB.Width];
if (colorA.A != 0 && colorB.A != 0)
{
return true;
}
}
}
return false;
}
}
}
使用此代码,每隔几帧动画就会检测到碰撞
IntersectPixels
用于检测碰撞。