This program is about driving fast and dodging the obstacles. I followed a couple of tutorials and managed to create an explosion class. Whenever a collision occurs, the explosion is meant to appear, but it doesn't.
There is no error, but I think the problem is in the Game1.cs. I created the following functions in the Game1.cs:
//list
List <Explosion> explosionList = new List<Explosion>();
//This is in the update method
foreach (Explosion ex in explosionList)
{
ex.Update(gameTime);
}
//This is a method called manage explosions
public void ManageExplosions()
{
for (int i = 0; i < explosionList.Count; i++)
{
if (explosionList[i].isVisible)
{
explosionList.RemoveAt(i);
i--;
}
}
}
//This is placed in the CheckCollision method
explosionList.Add(new Explosion(Content.Load<Texture2D>("Images/explosion3"), new Vector2(theHazard.Position.X, theHazard.Position.Y)));
Game1.cs
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace DriveFast
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
private Texture2D mCar;
private Texture2D mBackground;
private Texture2D mRoad;
private Texture2D mHazard;
private Texture2D hazardCrash;
private KeyboardState mPreviousKeyboardState;
private Vector2 mCarPosition = new Vector2(280, 440);
private int mMoveCarX = 160;
private int mVelocityY;
private double mNextHazardAppearsIn;
private int mCarsRemaining;
private int mHazardsPassed;
private int mIncreaseVelocity;
private double mExitCountDown = 10;
private int[] mRoadY = new int[2];
private List<Hazard> mHazards = new List<Hazard>();
private Random mRandom = new Random();
private SpriteFont mFont;
//video
List <Explosion> explosionList = new List<Explosion>();
private enum State
{
TitleScreen,
Running,
Crash,
GameOver,
Success
}
private State mCurrentState = State.TitleScreen;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.PreferredBackBufferHeight = 600;
graphics.PreferredBackBufferWidth = 800;
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
mCar = Content.Load<Texture2D>("Images/Car");
mBackground = Content.Load<Texture2D>("Images/Background");
mRoad = Content.Load<Texture2D>("Images/Road");
mHazard = Content.Load<Texture2D>("Images/Hazard");
hazardCrash = Content.Load<Texture2D>("Images/hazardCrash");
mFont = Content.Load<SpriteFont>("MyFont");
}
protected override void UnloadContent()
{
}
protected void StartGame()
{
mRoadY[0] = 0;
mRoadY[1] = -1 * mRoad.Height;
mHazardsPassed = 0;
mCarsRemaining = 3;
mVelocityY = 3;
mNextHazardAppearsIn = 1.5;
mIncreaseVelocity = 5;
mHazards.Clear();
mCurrentState = State.Running;
}
protected override void Update(GameTime gameTime)
{
KeyboardState aCurrentKeyboardState = Keyboard.GetState();
//Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed ||
aCurrentKeyboardState.IsKeyDown(Keys.Escape) == true)
{
this.Exit();
}
switch (mCurrentState)
{
case State.TitleScreen:
case State.Success:
case State.GameOver:
{
ExitCountdown(gameTime);
if (aCurrentKeyboardState.IsKeyDown(Keys.Space) == true && mPreviousKeyboardState.IsKeyDown(Keys.Space) == false)
{
StartGame();
}
break;
}
case State.Running:
{
//If the user has pressed the Spacebar, then make the car switch lanes
if (aCurrentKeyboardState.IsKeyDown(Keys.Space) == true && mPreviousKeyboardState.IsKeyDown(Keys.Space) == false)
{
mCarPosition.X += mMoveCarX;
mMoveCarX *= -1;
}
ScrollRoad();
foreach (Hazard aHazard in mHazards)
{
if (CheckCollision(aHazard) == true)
{
//video
explosionList.Add(new Explosion(Content.Load<Texture2D>("Images/explosion3"), new Vector2(aHazard.Position.X, aHazard.Position.Y)));
break;
}
MoveHazard(aHazard);
}
UpdateHazards(gameTime);
break;
}
case State.Crash:
{
//If the user has pressed the Space key, then resume driving
if (aCurrentKeyboardState.IsKeyDown(Keys.Space) == true && mPreviousKeyboardState.IsKeyDown(Keys.Space) == false)
{
mHazards.Clear();
mCurrentState = State.Running;
}
break;
}
}
mPreviousKeyboardState = aCurrentKeyboardState;
//video
ManageExplosions();
//
base.Update(gameTime);
//video
foreach (Explosion ex in explosionList)
{
ex.Update(gameTime);
}
}
private void ScrollRoad()
{
//Move the scrolling Road
for (int aIndex = 0; aIndex < mRoadY.Length; aIndex++)
{
if (mRoadY[aIndex] >= this.window.ClientBounds.Height)
{
int aLastRoadIndex = aIndex;
for (int aCounter = 0; aCounter < mRoadY.Length; aCounter++)
{
if (mRoadY[aCounter] < mRoadY[aLastRoadIndex])
{
aLastRoadIndex = aCounter;
}
}
mRoadY[aIndex] = mRoadY[aLastRoadIndex] - mRoad.Height;
}
}
for (int aIndex = 0; aIndex < mRoadY.Length; aIndex++)
{
mRoadY[aIndex] += mVelocityY;
}
}
private void MoveHazard(Hazard theHazard)
{
theHazard.Position.Y += mVelocityY;
if (theHazard.Position.Y > graphics.GraphicsDevice.Viewport.Height && theHazard.Visible == true)
{
theHazard.Visible = false;
mHazardsPassed += 1;
if (mHazardsPassed >= 100)
{
mCurrentState = State.Success;
mExitCountDown = 10;
}
mIncreaseVelocity -= 1;
if (mIncreaseVelocity < 0)
{
mIncreaseVelocity = 5;
mVelocityY += 1;
}
}
}
private void UpdateHazards(GameTime theGameTime)
{
mNextHazardAppearsIn -= theGameTime.ElapsedGameTime.TotalSeconds;
if (mNextHazardAppearsIn < 0)
{
int aLowerBound = 24 - (mVelocityY * 2);
int aUpperBound = 30 - (mVelocityY * 2);
if (mVelocityY > 10)
{
aLowerBound = 6;
aUpperBound = 8;
}
mNextHazardAppearsIn = (double)mRandom.Next(aLowerBound, aUpperBound) / 10;
AddHazard();
}
}
private void AddHazard()
{
int aRoadPosition = mRandom.Next(1, 3);
int aPosition = 275;
if (aRoadPosition == 2)
{
aPosition = 440;
}
bool aAddNewHazard = true;
foreach (Hazard aHazard in mHazards)
{
if (aHazard.Visible == false)
{
aAddNewHazard = false;
aHazard.Visible = true;
aHazard.Position = new Vector2(aPosition, -mHazard.Height);
break;
}
}
if (aAddNewHazard == true)
{
//Add a hazard to the left side of the Road
Hazard aHazard = new Hazard();
aHazard.Position = new Vector2(aPosition, -mHazard.Height);
mHazards.Add(aHazard);
}
}
private bool CheckCollision(Hazard theHazard)
{
BoundingBox aHazardBox = new BoundingBox(new Vector3(theHazard.Position.X, theHazard.Position.Y, 0), new Vector3(theHazard.Position.X + (mHazard.Width * .4f), theHazard.Position.Y + ((mHazard.Height - 50) * .4f), 0));
BoundingBox aCarBox = new BoundingBox(new Vector3(mCarPosition.X, mCarPosition.Y, 0), new Vector3(mCarPosition.X + (mCar.Width * .2f), mCarPosition.Y + (mCar.Height * .2f), 0));
if (aHazardBox.Intersects(aCarBox) == true)
{
//video
explosionList.Add(new Explosion(Content.Load<Texture2D>("Images/explosion3"), new Vector2(theHazard.Position.X, theHazard.Position.Y)));
mCurrentState = State.Crash;
mCarsRemaining -= 1;
if (mCarsRemaining < 0)
{
mCurrentState = State.GameOver;
mExitCountDown = 10;
}
return true;
}
return false;
}
private void ExitCountdown(GameTime theGameTime)
{
mExitCountDown -= theGameTime.ElapsedGameTime.TotalSeconds;
if (mExitCountDown < 0)
{
this.Exit();
}
}
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.Draw(mBackground, new Rectangle(graphics.GraphicsDevice.Viewport.X, graphics.GraphicsDevice.Viewport.Y, graphics.GraphicsDevice.Viewport.Width, graphics.GraphicsDevice.Viewport.Height), Color.White);
foreach (Explosion ex in explosionList)
{
ex.Draw(spriteBatch);
}
switch (mCurrentState)
{
case State.TitleScreen:
{
//Draw the display text for the Title screen
DrawTextCentered("Drive and avoid the hazards!", 200);
DrawTextCentered("Press 'Space' to start", 260);
DrawTextCentered("Exit in " + ((int)mExitCountDown).ToString(), 475);
break;
}
default:
{
DrawRoad();
DrawHazards();
spriteBatch.Draw(mCar, mCarPosition, new Rectangle(0, 0, mCar.Width, mCar.Height), Color.White, 0, new Vector2(0, 0), 0.2f, SpriteEffects.None, 0);
spriteBatch.DrawString(mFont, "Cars:", new Vector2(28, 520), Color.Brown, 0, new Vector2(0, 0), 1.0f, SpriteEffects.None, 0);
for (int aCounter = 0; aCounter < mCarsRemaining; aCounter++)
{
spriteBatch.Draw(mCar, new Vector2(25 + (30 * aCounter), 550), new Rectangle(0, 0, mCar.Width, mCar.Height), Color.White, 0, new Vector2(0, 0), 0.05f, SpriteEffects.None, 0);
}
spriteBatch.DrawString(mFont, "Hazards: " + mHazardsPassed.ToString(), new Vector2(5, 25), Color.Brown, 0, new Vector2(0, 0), 1.0f, SpriteEffects.None, 0);
if (mCurrentState == State.Crash)
{
DrawTextDisplayArea();
DrawTextCentered("Crash!", 200);
DrawTextCentered("Press 'Space' to continue driving.", 260);
}
else if (mCurrentState == State.GameOver)
{
DrawTextDisplayArea();
DrawTextCentered("Game Over.", 200);
DrawTextCentered("Press 'Space' to re-try.", 260);
DrawTextCentered("Exit in " + ((int)mExitCountDown).ToString(), 400);
}
else if (mCurrentState == State.Success)
{
DrawTextDisplayArea();
DrawTextCentered("Well Done!", 200);
DrawTextCentered("Press 'Space' to play again.", 260);
DrawTextCentered("Exit in " + ((int)mExitCountDown).ToString(), 400);
}
break;
}
}
spriteBatch.End();
base.Draw(gameTime);
}
private void DrawRoad()
{
for (int aIndex = 0; aIndex < mRoadY.Length; aIndex++)
{
if (mRoadY[aIndex] > mRoad.Height * -1 && mRoadY[aIndex] <= this.window.ClientBounds.Height)
{
spriteBatch.Draw(mRoad, new Rectangle((int)((this.window.ClientBounds.Width - mRoad.Width) / 2 - 18), mRoadY[aIndex], mRoad.Width, mRoad.Height + 5), Color.White);
}
}
}
private void DrawHazards()
{
foreach (Hazard aHazard in mHazards)
{
if (aHazard.Visible == true)
{
spriteBatch.Draw(mHazard, aHazard.Position, new Rectangle(0, 0, mHazard.Width, mHazard.Height), Color.White, 0, new Vector2(0, 0), 0.4f, SpriteEffects.None, 0);
}
}
}
private void DrawTextDisplayArea()
{
int aPositionX = (int)((graphics.GraphicsDevice.Viewport.Width / 2) - (450 / 2));
spriteBatch.Draw(mBackground, new Rectangle(aPositionX, 75, 450, 400), Color.White);
}
private void DrawTextCentered(string theDisplayText, int thePositionY)
{
Vector2 aSize = mFont.MeasureString(theDisplayText);
int aPositionX = (int)((graphics.GraphicsDevice.Viewport.Width / 2) - (aSize.X / 2));
spriteBatch.DrawString(mFont, theDisplayText, new Vector2(aPositionX, thePositionY), Color.Beige, 0, new Vector2(0, 0), 1.0f, SpriteEffects.None, 0);
spriteBatch.DrawString(mFont, theDisplayText, new Vector2(aPositionX + 1, thePositionY + 1), Color.Brown, 0, new Vector2(0, 0), 1.0f, SpriteEffects.None, 0);
}
//video
//manage explosions
public void ManageExplosions()
{
for (int i = 0; i < explosionList.Count; i++)
{
if (explosionList[i].isVisible)
{
explosionList.RemoveAt(i);
i--;
}
}
}
}
}
Explosion.cs
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace DriveFast
{
public class Explosion
{
public Texture2D texture;
public Vector2 position;
public float timer;
public float interval;
public Vector2 origin;
public int currentFrame, spriteWidth, spriteHeight;
public Rectangle sourceRect;
public bool isVisible;
//Constructor
public Explosion(Texture2D newTexture, Vector2 newPosition)
{
position = newPosition;
texture = newTexture;
timer = 0;
interval = 20f;
currentFrame = 1;
spriteWidth = 128;
spriteHeight = 128;
isVisible = true;
}
//load content
public void LoadContent(ContentManager Content)
{
}
//update
public void Update(GameTime gameTime)
{
//increase
timer += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
if (timer > interval)
{
currentFrame++;
timer = 0f;
}
if (currentFrame == 17)
{
isVisible = false;
currentFrame = 0;
}
sourceRect = new Rectangle(currentFrame * spriteWidth, 0, spriteWidth, spriteHeight);
origin = new Vector2(sourceRect.Width / 2, sourceRect.Height / 2);
}
//draw
public void Draw(SpriteBatch spriteBatch)
{
if (isVisible == true)
{
spriteBatch.Draw(texture, position, sourceRect, Color.White, 0f, origin, 1.0f, SpriteEffects.None, 0);
}
}
}
}
Hazard.cs
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
namespace DriveFast
{
class Hazard
{
public Vector2 Position;
public bool Visible = true;
public Hazard()
{
}
}
}
First of all you need to draw your Explosions after road, car, hazards etc. Replace next code as shown below:
DrawRoad();
DrawHazards();
spriteBatch.Draw(mCar, mCarPosition, new Rectangle(0, 0, mCar.Width, mCar.Height), Color.White, 0, new Vector2(0, 0), 0.2f, SpriteEffects.None, 0);
// place code here
foreach (Explosion ex in explosionList)
{
ex.Draw(spriteBatch);
}
//
Into manage explosion method make !isVisible instead of isVisible:
public void ManageExplosions()
{
for (int i = 0; i < explosionList.Count; i++)
{
if (!explosionList[i].isVisible)
{
explosionList.RemoveAt(i);
i--;
}
}
}
Remove line:
foreach (Hazard aHazard in mHazards)
{
if (CheckCollision(aHazard) == true)
{
//remove next line because it is duplicate of adding Explosion which is already added inside CheckCollision(Hazard) method
//explosionList.Add(new Explosion(Content.Load<Texture2D>("Images/explosion3"), new Vector2(aHazard.Position.X, aHazard.Position.Y)));
break;
}
MoveHazard(aHazard);
}
Change next variables:
spriteWidth = 71;//128;
spriteHeight = 100;//128;
sourceRect = new Rectangle(currentFrame * spriteWidth, 0, spriteWidth, spriteHeight);
//origin = new Vector2(sourceRect.Width / 2, sourceRect.Height / 2);
origin = new Vector2(-(sourceRect.Width / 4), 0);
Comment next code for testing:
if (mCurrentState == State.Crash)
{
//DrawTextDisplayArea();
//DrawTextCentered("Crash!", 200);
//DrawTextCentered("Press 'Space' to continue driving.", 260);
}
Related
I'm making on some Winform application, I noticed my program's memory issue.
This is my winform custom control code.
using System;
using System.Drawing;
using System.Windows.Forms;
using DX = SharpDX;
using D2D = SharpDX.Direct2D1;
using SharpDX.Mathematics.Interop;
using DW = SharpDX.DirectWrite;
namespace WinFormTest
{
public partial class BitmapSurface : Control
{
D2D.Factory d2dFactory;
DW.Factory dwFactory;
D2D.WindowRenderTarget wrt;
D2D.BitmapRenderTarget brt;
Rectangle clippingRect = new Rectangle(0, 0, 100, 100);
public BitmapSurface()
{
InitializeComponent();
InitializeRenderer();
}
DX.Size2 clientSize2;
DX.Size2F clientSize2f;
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
if (clientSize2 == null)
clientSize2 = new DX.Size2();
if (clientSize2f == null)
clientSize2f = new DX.Size2F();
clientSize2.Width = ClientSize.Width;
clientSize2.Height = ClientSize.Height;
clientSize2f.Width = ClientSize.Width;
clientSize2f.Height = ClientSize.Height;
if (wrt != null)
{
wrt.Resize(clientSize2);
}
if (brt != null)
{
brt.Dispose();
brt = new D2D.BitmapRenderTarget(wrt, D2D.CompatibleRenderTargetOptions.None, clientSize2f, null, null);
brt.AntialiasMode = D2D.AntialiasMode.Aliased;
}
this.Invalidate();
}
private D2D.SolidColorBrush GetBrush(float r, float g, float b, float a = 255)
{
var brush = new D2D.SolidColorBrush(
wrt, new RawColor4(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f));
return brush;
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
clippingRect = this.ClientRectangle;
var rect = clippingRect;
DrawBitmap();
}
public void InitializeRenderer()
{
int width = this.ClientSize.Width;
int height = this.ClientSize.Height;
D2D.HwndRenderTargetProperties hrtp = new D2D.HwndRenderTargetProperties();
hrtp.Hwnd = this.Handle;
hrtp.PixelSize = new DX.Size2(width, height);
// D2DFactory
if (d2dFactory == null)
d2dFactory = new D2D.Factory();
// DirectWrite
if (dwFactory == null)
dwFactory = new DW.Factory();
wrt = new D2D.WindowRenderTarget(d2dFactory, new D2D.RenderTargetProperties(), hrtp);
wrt.AntialiasMode = D2D.AntialiasMode.Aliased;
brt = new D2D.BitmapRenderTarget(wrt, D2D.CompatibleRenderTargetOptions.None, new DX.Size2F(width, height), null, null);
brt.AntialiasMode = D2D.AntialiasMode.Aliased;
}
public void DrawBitmap()
{
brt.BeginDraw();
brt.Clear(new RawColor4(0, 0, 0, 1));
// Draw Something
for (int i = 0; i < 1000; i++)
{
brt.DrawLine(
new RawVector2(0, i),
new RawVector2(90, 90 + i),
GetBrush(255, 255, 255));
}
for (int i = 0; i < 1000; i++)
{
brt.FillRectangle(
new RawRectangleF(90, 0 + i, 150, 10 + i),
GetBrush(255 - i, 255 - i, 255 - i));
}
brt.EndDraw();
wrt.BeginDraw();
wrt.DrawBitmap(brt.Bitmap, 1, D2D.BitmapInterpolationMode.NearestNeighbor);
wrt.EndDraw();
}
}
}
My program's mainform can have many childs, Child draw somethings with SharpDX.
Memory usage is increase When I open child forms, but after closing child form and GC.Collect memory usage is NOT decrease.
Is this bad usage for SharpDX?
Implementing the Webview based application for Android TV with no of links to the website landing on Video pages. The web page being desktop, it is very difficult to use the D-Pad keys to navigate. I would like to implement the Mouse cursor kind of navigation controlled by D-Pad. Any help to available sample source code would help.
Trying to do the same thing here.
Basic approach:
Create a custom view that draws, moves and animates a cursor
In a Frame Layout add this custom cursor view on top of your webview
When the user clicks (key: DPAD center), simulate a click on the position of your cursor via simulated touch events
Scroll the WebView on a corresponding button press when the cursor is at the edge
The focus handling is a bit of a PITA when doing this, though:
The webview does all kinds of weird stuff (scrolling, highlighting,...) when it has focus. So I tried having my cursor view focused. Works perfectly fine, except when it comes to clicking text input fields -> keyboard won't show/work if the WebView isn't focused.
So, using getHitTestResult() we can find out if our click will hit an input field and make the WebView have focus before. That works fine, but I haven't yet found a reliable way to hand the focus back to my cursor view when the user is done entering text.
One thing I tried was getting a hook on the IME connection, but I couldn't quite get this approach to be stable enough for using it in a public app.
To Enable cursor pointer in android tv webview by creating custom pointer layout
public class CursorLayout extends FrameLayout {
public static final int CURSOR_DISAPPEAR_TIMEOUT = 5000;
public static int CURSOR_RADIUS = 0;
public static float CURSOR_STROKE_WIDTH = 0.0f;
public static float MAX_CURSOR_SPEED = 0.0f;
public static int SCROLL_START_PADDING = 100;
public static final int UNCHANGED = -100;
public int EFFECT_DIAMETER;
public int EFFECT_RADIUS;
private Callback callback;
/* access modifiers changed from: private */
public Point cursorDirection = new Point(0, 0);
/* access modifiers changed from: private */
public Runnable cursorHideRunnable = new Runnable() {
public void run() {
CursorLayout.this.invalidate();
}
};
/* access modifiers changed from: private */
public PointF cursorPosition = new PointF(0.0f, 0.0f);
/* access modifiers changed from: private */
public PointF cursorSpeed = new PointF(0.0f, 0.0f);
private Runnable cursorUpdateRunnable = new Runnable() {
public void run() {
if (CursorLayout.this.getHandler() != null) {
CursorLayout.this.getHandler().removeCallbacks(CursorLayout.this.cursorHideRunnable);
}
long currentTimeMillis = System.currentTimeMillis();
long access$100 = currentTimeMillis - CursorLayout.this.lastCursorUpdate;
CursorLayout.this.lastCursorUpdate = currentTimeMillis;
float f = ((float) access$100) * 0.05f;
PointF access$200 = CursorLayout.this.cursorSpeed;
CursorLayout cursorLayout = CursorLayout.this;
float f2 = cursorLayout.cursorSpeed.x;
CursorLayout cursorLayout2 = CursorLayout.this;
float access$400 = cursorLayout.bound(f2 + (cursorLayout2.bound((float) cursorLayout2.cursorDirection.x, 1.0f) * f), CursorLayout.MAX_CURSOR_SPEED);
CursorLayout cursorLayout3 = CursorLayout.this;
float f3 = cursorLayout3.cursorSpeed.y;
CursorLayout cursorLayout4 = CursorLayout.this;
access$200.set(access$400, cursorLayout3.bound(f3 + (cursorLayout4.bound((float) cursorLayout4.cursorDirection.y, 1.0f) * f), CursorLayout.MAX_CURSOR_SPEED));
if (Math.abs(CursorLayout.this.cursorSpeed.x) < 0.1f) {
CursorLayout.this.cursorSpeed.x = 0.0f;
}
if (Math.abs(CursorLayout.this.cursorSpeed.y) < 0.1f) {
CursorLayout.this.cursorSpeed.y = 0.0f;
}
if (CursorLayout.this.cursorDirection.x == 0 && CursorLayout.this.cursorDirection.y == 0 && CursorLayout.this.cursorSpeed.x == 0.0f && CursorLayout.this.cursorSpeed.y == 0.0f) {
if (CursorLayout.this.getHandler() != null) {
CursorLayout.this.getHandler().postDelayed(CursorLayout.this.cursorHideRunnable, 5000);
}
return;
}
CursorLayout.this.tmpPointF.set(CursorLayout.this.cursorPosition);
CursorLayout.this.cursorPosition.offset(CursorLayout.this.cursorSpeed.x, CursorLayout.this.cursorSpeed.y);
Log.d("cursor1234_xxxx", String.valueOf(CursorLayout.this.cursorPosition.x));
Log.d("cursor1234_yyyy", String.valueOf(CursorLayout.this.cursorPosition.y));
if (CursorLayout.this.cursorPosition.x < 0.0f) {
CursorLayout.this.cursorPosition.x = 0.0f;
} else if (CursorLayout.this.cursorPosition.x > ((float) (CursorLayout.this.getWidth() - 1))) {
CursorLayout.this.cursorPosition.x = (float) (CursorLayout.this.getWidth() - 1);
}
if (CursorLayout.this.cursorPosition.y < 0.0f) {
CursorLayout.this.cursorPosition.y = 0.0f;
} else if (CursorLayout.this.cursorPosition.y > ((float) (CursorLayout.this.getHeight() - 1))) {
CursorLayout.this.cursorPosition.y = (float) (CursorLayout.this.getHeight() - 1);
}
if (!CursorLayout.this.tmpPointF.equals(CursorLayout.this.cursorPosition) && CursorLayout.this.dpadCenterPressed) {
CursorLayout cursorLayout5 = CursorLayout.this;
cursorLayout5.dispatchMotionEvent(cursorLayout5.cursorPosition.x, CursorLayout.this.cursorPosition.y, 2);
}
View childAt = CursorLayout.this.getChildAt(0);
if (childAt != null) {
if (CursorLayout.this.cursorPosition.y > ((float) (CursorLayout.this.getHeight() - CursorLayout.SCROLL_START_PADDING))) {
if (CursorLayout.this.cursorSpeed.y > 0.0f && childAt.canScrollVertically((int) CursorLayout.this.cursorSpeed.y)) {
childAt.scrollTo(childAt.getScrollX(), childAt.getScrollY() + ((int) CursorLayout.this.cursorSpeed.y));
}
} else if (CursorLayout.this.cursorPosition.y < ((float) CursorLayout.SCROLL_START_PADDING) && CursorLayout.this.cursorSpeed.y < 0.0f && childAt.canScrollVertically((int) CursorLayout.this.cursorSpeed.y)) {
childAt.scrollTo(childAt.getScrollX(), childAt.getScrollY() + ((int) CursorLayout.this.cursorSpeed.y));
}
if (CursorLayout.this.cursorPosition.x > ((float) (CursorLayout.this.getWidth() - CursorLayout.SCROLL_START_PADDING))) {
if (CursorLayout.this.cursorSpeed.x > 0.0f && childAt.canScrollHorizontally((int) CursorLayout.this.cursorSpeed.x)) {
childAt.scrollTo(childAt.getScrollX() + ((int) CursorLayout.this.cursorSpeed.x), childAt.getScrollY());
}
} else if (CursorLayout.this.cursorPosition.x < ((float) CursorLayout.SCROLL_START_PADDING) && CursorLayout.this.cursorSpeed.x < 0.0f && childAt.canScrollHorizontally((int) CursorLayout.this.cursorSpeed.x)) {
childAt.scrollTo(childAt.getScrollX() + ((int) CursorLayout.this.cursorSpeed.x), childAt.getScrollY());
}
}
CursorLayout.this.invalidate();
if (CursorLayout.this.getHandler() != null) {
CursorLayout.this.getHandler().post(this);
}
}
};
/* access modifiers changed from: private */
public boolean dpadCenterPressed = false;
/* access modifiers changed from: private */
public long lastCursorUpdate = System.currentTimeMillis();
private Paint paint = new Paint();
PointF tmpPointF = new PointF();
public interface Callback {
void onUserInteraction();
}
/* access modifiers changed from: private */
public float bound(float f, float f2) {
if (f > f2) {
return f2;
}
float f3 = -f2;
return f < f3 ? f3 : f;
}
public CursorLayout(Context context) {
super(context);
init();
}
public CursorLayout(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
init();
}
private void init() {
if (!isInEditMode()) {
this.paint.setAntiAlias(true);
setWillNotDraw(false);
Display defaultDisplay = ((WindowManager) getContext().getSystemService(getContext().WINDOW_SERVICE)).getDefaultDisplay();
Point point = new Point();
defaultDisplay.getSize(point);
this.EFFECT_RADIUS = point.x / 20;
this.EFFECT_DIAMETER = this.EFFECT_RADIUS * 2;
CURSOR_STROKE_WIDTH = (float) (point.x / 400);
CURSOR_RADIUS = point.x / 110;
MAX_CURSOR_SPEED = (float) (point.x / 25);
SCROLL_START_PADDING = point.x / 15;
}
}
public void setCallback(Callback callback2) {
this.callback = callback2;
}
public boolean onInterceptTouchEvent(MotionEvent motionEvent) {
Callback callback2 = this.callback;
if (callback2 != null) {
callback2.onUserInteraction();
}
return super.onInterceptTouchEvent(motionEvent);
}
/* access modifiers changed from: protected */
public void onSizeChanged(int i, int i2, int i3, int i4) {
super.onSizeChanged(i, i2, i3, i4);
UtilMethods.LogMethod("cursorView123_", "onSizeChanged");
if (!isInEditMode()) {
this.cursorPosition.set(((float) i) / 2.0f, ((float) i2) / 2.0f);
if (getHandler() != null) {
getHandler().postDelayed(this.cursorHideRunnable, 5000);
}
}
}
public boolean dispatchKeyEvent(KeyEvent keyEvent) {
UtilMethods.LogMethod("cursorView123_", "dispatchKeyEvent");
Callback callback2 = this.callback;
if (callback2 != null) {
callback2.onUserInteraction();
}
int keyCode = keyEvent.getKeyCode();
if (!(keyCode == 66 || keyCode == 160)) {
switch (keyCode) {
case 19:
if (keyEvent.getAction() == 0) {
if (this.cursorPosition.y <= 0.0f) {
return super.dispatchKeyEvent(keyEvent);
}
handleDirectionKeyEvent(keyEvent, -100, -1, true);
} else if (keyEvent.getAction() == 1) {
handleDirectionKeyEvent(keyEvent, -100, 0, false);
}
return true;
case 20:
if (keyEvent.getAction() == 0) {
if (this.cursorPosition.y >= ((float) getHeight())) {
return super.dispatchKeyEvent(keyEvent);
}
handleDirectionKeyEvent(keyEvent, -100, 1, true);
} else if (keyEvent.getAction() == 1) {
handleDirectionKeyEvent(keyEvent, -100, 0, false);
}
return true;
case 21:
if (keyEvent.getAction() == 0) {
if (this.cursorPosition.x <= 0.0f) {
return super.dispatchKeyEvent(keyEvent);
}
handleDirectionKeyEvent(keyEvent, -1, -100, true);
} else if (keyEvent.getAction() == 1) {
handleDirectionKeyEvent(keyEvent, 0, -100, false);
}
return true;
case 22:
if (keyEvent.getAction() == 0) {
if (this.cursorPosition.x >= ((float) getWidth())) {
return super.dispatchKeyEvent(keyEvent);
}
handleDirectionKeyEvent(keyEvent, 1, -100, true);
} else if (keyEvent.getAction() == 1) {
handleDirectionKeyEvent(keyEvent, 0, -100, false);
}
return true;
case 23:
break;
default:
switch (keyCode) {
case 268:
if (keyEvent.getAction() == 0) {
handleDirectionKeyEvent(keyEvent, -1, -1, true);
} else if (keyEvent.getAction() == 1) {
handleDirectionKeyEvent(keyEvent, 0, 0, false);
}
return true;
case 269:
if (keyEvent.getAction() == 0) {
handleDirectionKeyEvent(keyEvent, -1, 1, true);
} else if (keyEvent.getAction() == 1) {
handleDirectionKeyEvent(keyEvent, 0, 0, false);
}
return true;
case 270:
if (keyEvent.getAction() == 0) {
handleDirectionKeyEvent(keyEvent, 1, -1, true);
} else if (keyEvent.getAction() == 1) {
handleDirectionKeyEvent(keyEvent, 0, 0, false);
}
return true;
case 271:
if (keyEvent.getAction() == 0) {
handleDirectionKeyEvent(keyEvent, 1, 1, true);
} else if (keyEvent.getAction() == 1) {
handleDirectionKeyEvent(keyEvent, 0, 0, false);
}
return true;
}
}
}
if (!isCursorDissappear()) {
if (keyEvent.getAction() == 0 && !getKeyDispatcherState().isTracking(keyEvent)) {
getKeyDispatcherState().startTracking(keyEvent, this);
this.dpadCenterPressed = true;
dispatchMotionEvent(this.cursorPosition.x, this.cursorPosition.y, 0);
} else if (keyEvent.getAction() == 1) {
getKeyDispatcherState().handleUpEvent(keyEvent);
dispatchMotionEvent(this.cursorPosition.x, this.cursorPosition.y, 1);
this.dpadCenterPressed = false;
}
return true;
}
return super.dispatchKeyEvent(keyEvent);
}
/* access modifiers changed from: private */
public void dispatchMotionEvent(float f, float f2, int i) {
UtilMethods.LogMethod("cursorView123_", "dispatchMotionEvent");
long uptimeMillis = SystemClock.uptimeMillis();
long uptimeMillis2 = SystemClock.uptimeMillis();
PointerProperties pointerProperties = new PointerProperties();
pointerProperties.id = 0;
pointerProperties.toolType = 1;
PointerProperties[] pointerPropertiesArr = {pointerProperties};
PointerCoords pointerCoords = new PointerCoords();
pointerCoords.x = f;
pointerCoords.y = f2;
pointerCoords.pressure = 1.0f;
pointerCoords.size = 1.0f;
dispatchTouchEvent(MotionEvent.obtain(uptimeMillis, uptimeMillis2, i, 1, pointerPropertiesArr, new PointerCoords[]{pointerCoords}, 0, 0, 1.0f, 1.0f, 0, 0, 0, 0));
}
private void handleDirectionKeyEvent(KeyEvent keyEvent, int i, int i2, boolean z) {
this.lastCursorUpdate = System.currentTimeMillis();
if (!z) {
getKeyDispatcherState().handleUpEvent(keyEvent);
this.cursorSpeed.set(0.0f, 0.0f);
} else if (!getKeyDispatcherState().isTracking(keyEvent)) {
Handler handler = getHandler();
handler.removeCallbacks(this.cursorUpdateRunnable);
handler.post(this.cursorUpdateRunnable);
getKeyDispatcherState().startTracking(keyEvent, this);
} else {
return;
}
Point point = this.cursorDirection;
if (i == -100) {
i = point.x;
}
if (i2 == -100) {
i2 = this.cursorDirection.y;
}
point.set(i, i2);
}
/* access modifiers changed from: protected */
public void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
UtilMethods.LogMethod("cursorView123_", "dispatchDraw");
if (!isInEditMode() && !isCursorDissappear()) {
float f = this.cursorPosition.x;
float f2 = this.cursorPosition.y;
this.paint.setColor(Color.argb(128, 255, 255, 255));
this.paint.setStyle(Style.FILL);
canvas.drawCircle(f, f2, (float) CURSOR_RADIUS, this.paint);
this.paint.setColor(-7829368);
this.paint.setStrokeWidth(CURSOR_STROKE_WIDTH);
this.paint.setStyle(Style.STROKE);
canvas.drawCircle(f, f2, (float) CURSOR_RADIUS, this.paint);
}
}
private boolean isCursorDissappear() {
return System.currentTimeMillis() - this.lastCursorUpdate > 5000;
}
/* access modifiers changed from: protected */
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
}}
then put the webview inside custom cursor layout in XML
<com.example.webviewtvapp.CursorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/cursorLayout">
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</com.example.webviewtvapp.CursorLayout>
I'm trying to draw a line from the player to a targets asteroid as a "Grapple" hook, i've found some examples for doing this in 2D in xna but my "Position" and "origin" vector2 seems to change depending on who and when they are used. In the case of the lines they appear to draw up and right of the position (roughly 100 pixels) in the opposite direction of the target and rotate about an origin somewhere to the left of the target as the player moves.
here is the player code including the grapple code and target assignment
namespace Sparatius.Sprites
{
public class PlayerSprite : BaseSprite
{
ControlInput controlInput;
Texture2D Grapple;
SpriteFont font;
bool LeftGrapple = false, RightGrapple = false;
int GrappleRange = 300;
Sprites.AsteroidSprite LeftTarget, RightTarget;
public BoundingSphere grappleHitBox
{
get { return new BoundingSphere(new Vector3(Position.X + Origin.X, Position.Y + Origin.Y, 0), GrappleRange); }
}
public float speed
{
get { return Speed; }
}
public PlayerSprite(Vector2 spriteLocal)
:base(spriteLocal)
{
this.Rotation = 0;
this.Speed = 0;
this.FrameCount = new Point(4, 2);
this.ColorTint = Color.White;
this.controlInput = new ControlInput();
}
public void LoadContent(ContentManager content)
{
Texture = content.Load<Texture2D>("Sprites/PinballSpin");
font = content.Load<SpriteFont>("Fonts/Font1");
Grapple = content.Load<Texture2D>("Sprites/Grapple");
FrameSize = new Point((int)Texture.Width / FrameCount.X, (int)Texture.Height / FrameCount.Y);
Origin = new Vector2(FrameSize.X / 2, FrameSize.Y / 2);
Animation = new Animation(Texture, FrameSize);
}
public override void Update(GameTime gameTime)
{
base.Update(gameTime);
controlInput.GetControlStates();
if (controlInput.JustPressed(Keys.W))
Speed += 2;
else if (controlInput.JustPressed(Keys.S))
Speed -= 2;
if (controlInput.IsHeld(Keys.A))
Rotation -= 0.05f;
if (controlInput.IsHeld(Keys.D))
Rotation += 0.05f;
if (LeftTarget != null)
{
LeftTarget.Distance = Vector2.Distance(Position, LeftTarget.Position);
if (LeftTarget.Distance > GrappleRange)
{
LeftTarget.isTarget = false;
LeftTarget = null;
}
if (controlInput.IsHeld(Keys.Q))
{
LeftGrapple = true;
}
else
LeftGrapple = false;
}
if (RightTarget != null)
{
RightTarget.Distance = Vector2.Distance(Position, RightTarget.Position);
if (RightTarget.Distance > GrappleRange)
{
RightTarget.isTarget = false;
RightTarget = null;
}
if (controlInput.IsHeld(Keys.E))
{
RightGrapple = true;
}
else
RightGrapple = false;
}
}
public override void Draw(SpriteBatch spriteBatch)
{
base.Draw(spriteBatch);
if (LeftGrapple)
{
float leftRotation = (float)Math.Atan2(LeftTarget.Position.Y - Position.Y, LeftTarget.Position.X - Position.X);
//spriteBatch.Draw(Texture, Position, null, ColorTint, leftRotation, Position, 1f, SpriteEffects.None, 0f);
spriteBatch.Draw(Grapple,
new Rectangle((int)Position.X, (int)Position.Y, 2, (int)LeftTarget.Distance),
null, Color.Blue, leftRotation, Position, SpriteEffects.None, 0f);
}
if (RightGrapple)
{
float rightRotation = (float)Math.Atan2(RightTarget.Position.Y - Position.Y, RightTarget.Position.X - Position.X);
//spriteBatch.Draw(Texture, Position, null, ColorTint, rightRotation, Position, 1f, SpriteEffects.None, 0f);
spriteBatch.Draw(Grapple,
new Rectangle((int)Position.X, (int)Position.Y, 2, (int)RightTarget.Distance),
null, Color.Blue, rightRotation, Position, SpriteEffects.None, 0f);
}
spriteBatch.DrawString(font, "Player Rotation: " + Rotation, Position, Color.Red);
spriteBatch.DrawString(font, "Player RoationDegree: " + (int)MathHelper.ToDegrees(Rotation), origin, Color.Blue);
}
public void GrappleCheck(AsteroidSprite target)
{
float targetTragectory = (float)Math.Atan2(Position.Y - target.Position.Y, Position.X - target.Position.X);
if ((targetTragectory < (rotation - (float)MathHelper.PiOver4)) && ((targetTragectory > (rotation - (float)MathHelper.Pi + (float)MathHelper.PiOver4))))
{
target.Distance = Vector2.Distance(Position, target.Position);
if (LeftTarget != null)
{
if (LeftTarget.Distance > target.Distance)
{
LeftTarget.isTarget = false;
LeftTarget = target;
LeftTarget.isTarget = true;
}
}
else
{
LeftTarget = target;
LeftTarget.isTarget = true;
}
}
if ((targetTragectory > (rotation + (float)MathHelper.PiOver4)) && ((targetTragectory < (rotation + (float)MathHelper.Pi - (float)MathHelper.PiOver4))))
{
target.Distance = Vector2.Distance(Position, target.Position);
if (RightTarget != null)
{
if (RightTarget.Distance > target.Distance)
{
RightTarget.isTarget = false;
RightTarget = target;
RightTarget.isTarget = true;
}
}
else
{
RightTarget = target;
RightTarget.isTarget = true;
}
}
}
}
}
any idea whats going wrong? cheers
public static void DrawLine(SpriteBatch spriteBatch, Vector2 begin, Vector2 end, Color color, int width = 1)
{
Rectangle r = new Rectangle((int)begin.X, (int)begin.Y, (int)(end - begin).Length()+width, width);
Vector2 v = Vector2.Normalize(begin - end);
float angle = (float)Math.Acos(Vector2.Dot(v, -Vector2.UnitX));
if (begin.Y > end.Y) angle = MathHelper.TwoPi - angle;
spriteBatch.Draw(Pixel, r, null, color, angle, Vector2.Zero, SpriteEffects.None, 0);
}
Pixel is just a 1x1 sprite
You can also use the this keyword to make a handy extension method.
hi i am new to processing and i'm trying to figure out how to make the sphere move from left to right using a marker instead of the mouse. can you help me please? i can use the marker to shoot but i cant move the sphere by shooting
import TUIO.*;
TuioProcessing tuioClient;
HashMap symbols=new HashMap();
PFont fontA;
int sphereDiameter = 50;
boolean shoot = false;
float obj_size = 60;
int randx()
{
return int(random(600));
}
int[] sphereXCoords = { randx(), randx(), randx(), randx(), randx() };
int[] sphereYCoords = { 0, 0, 0, 0, 0 };
void setup()
{
size(1000,700);
tuioClient = new TuioProcessing(this);
}
void draw()
{
Vector<TuioObject> tuioObjectList =tuioClient.getTuioObjects();
Collections.sort(tuioObjectList, comp);
for (TuioObject tobj:tuioObjectList) {
fill(50, 50, 100);
int id = tobj.getSymbolID();
int x = tobj.getScreenX(width);
int y = tobj.getScreenY(height);
rect(x, y, obj_size, obj_size);
String txt="?";
if (symbols.containsKey(id)) {// if it's one in symbols, then look it up
txt = (String)symbols.get(id);
}
fill(255);
text(txt, x, y);
}
int[] sphereXCoords = { randx(), randx(), randx(), randx(), randx() };
fill(100, 0, 0);
// draw the answer box
// ellipse(answerX, answerY, obj_size, obj_size);
fill(255);
// write the answer text
// text(""+answer, answerX, answerY);
background(1);
fill(color(255,255,0));
stroke(color(0,255,0));
triangle(mouseX-8, 580, mouseX+8, 580, mouseX, 565);
fill(color(255,0,0));
stroke(color(255,0,0));
if(shoot==true)
{
sphereKiller( mouseX);
shoot = false;
}
sphereDropper();
//gameEnder();
}
Comparator<TuioObject> comp = new Comparator<TuioObject>() {
// Comparator object to compare two TuioObjects on the basis of their x position
// Returns -1 if o1 left of o2; 0 if they have same x pos; 1 if o1 right of o2
public int compare(TuioObject o1, TuioObject o2) {
if (o1.getX()<o2.getX()) {
return -1;
}
else if (o1.getX()>o2.getX()) {
return 1;
}
else {
return 0;
}
}
};
void mousePressed()
{
shoot = true;
}
void sphereDropper()
{
stroke(255);
fill(255);
for (int i=0; i<5; i++)
{
ellipse(sphereXCoords[i], sphereYCoords[i]++,
sphereDiameter, sphereDiameter);
}
}
void sphereKiller(int shotX)
{
boolean hit = false;
for (int i = 0; i < 5; i++)
{
if((shotX >= (sphereXCoords[i]-sphereDiameter/2)) &&
(shotX <= (sphereXCoords[i]+sphereDiameter/2)))
{
hit = true;
line(mouseX, 565, mouseX, sphereYCoords[i]);
ellipse(sphereXCoords[i], sphereYCoords[i],
sphereDiameter+25, sphereDiameter+25);
sphereXCoords[i] = randx();
sphereYCoords[i] = 0;
}
}
if(hit == false)
{
line(mouseX, 565, mouseX, 0);
}
}
/* void gameEnder()
{
for (int i=0; i< 5; i++)
{
if(sphereYCoords[i]==600)
{
fill(color(255,0,0));
noLoop();
}
}
}*/
void addTuioObject(TuioObject tobj) {
}
// called when an object is removed from the scene
void removeTuioObject(TuioObject tobj) {
}
/ / called when an object is moved
void updateTuioObject (TuioObject tobj) {
if(tobj.getSymbolID() == 32)
{
shoot = true;
}
}
// called when a cursor is added to the scene
void addTuioCursor(TuioCursor tcur) {
}
// called when a cursor is moved
void updateTuioCursor (TuioCursor tcur) {
}
// called when a cursor is removed from the scene
void removeTuioCursor(TuioCursor tcur) {
}
// called after each message bundle
// representing the end of an image frame
void refresh(TuioTime bundleTime) {
//redraw();
}
What do you mean by "shooting" ?
So you have your tuioClient and you initialize it in setup(). Thats good, because then the callback methods (addTuioObject, removeTuioObject, updateTuioObject, addTuioCursor, updateTuioCursor, removeTuioCursor, refresh) will fire whenever your sketch receives a TUIO message.
Keep in mind that TUIO is based on OSC which is transported over UDP. That means the tracker (reactivision & co) will have to send to the IP and port your sketch is listening to. If both are on the same machine use 127.0.0.1 and port 3333 (default).
Have a look at the examples. You'll find them in the processing "IDE" click:
"File -> Examples"
and Navigate to
"Contributed Libraries -> TUIO"
I am making a game where characters come from opposite sides of the screen and collide and attack each other then they are removed when they die. I have managed to enable the lists to stop moving and do damage when they collide but my problem is when 2 of them collide all of them stop moving.
My code for the shortswordsman collisions is:
private void shortMoveCollisions(GameTime gameTime)
{
Rectangle shortRect;
int shortSpeed = 2;
int shortDamage = 20;
bool collided = false;
for (int i = 0; i < shortList.Count; i++)
{
List<Goblin> tempGoblinList = new List<Goblin>(goblinList);
shortRect = new Rectangle((int)shortList[i].position.X, (int)shortList[i].position.Y, ShortSwordsman.texture.Width / 4 - 20, ShortSwordsman.texture.Height);
foreach (Goblin goblin in tempGoblinList)
{
Rectangle goblinRect = new Rectangle((int)goblin.position.X, (int)goblin.position.Y, Goblin.texture.Width / 4 - 20, Goblin.texture.Height);
if (shortRect.Intersects(goblinRect))
{
collided = true;
shortList[i].AnimateAttack(gameTime);
shortTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (shortTimer >= shortDelay)
{
shortTimer -= shortDelay;
goblin.health -= shortDamage;
if (goblin.health <= 0)
{
goblinList.Remove(goblin);
}
}
}
}
if (shortRect.Intersects(background.badCastleRect))
{
collided = true;
shortList[i].AnimateAttack(gameTime);
shortTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (shortTimer >= shortDelay)
{
shortTimer -= shortDelay;
badCastleHealth -= shortDamage;
}
}
if (collided == false)
{
shortList[i].AnimateWalk(gameTime);
shortList[i].position.X += shortSpeed;
}
}
}
And my code for the goblins collisions is:
private void GoblinMoveCollisions(GameTime gameTime)
{
Rectangle goblinRect;
int goblinSpeed = 2;
int goblinDamage = 20;
bool collided = false;
for (int i = 0; i < goblinList.Count; i++)
{
List<ShortSwordsman> tempShortList = new List<ShortSwordsman>(shortList);
goblinRect = new Rectangle((int)goblinList[i].position.X, (int)goblinList[i].position.Y, Goblin.texture.Width / 4 - 20, Goblin.texture.Height);
foreach (ShortSwordsman shortSwordsman in tempShortList)
{
Rectangle shortRect = new Rectangle((int)shortSwordsman.position.X, (int)shortSwordsman.position.Y, ShortSwordsman.texture.Width / 4 - 20, ShortSwordsman.texture.Height);
if (goblinRect.Intersects(shortRect))
{
collided = true;
goblinList[i].AnimateAttack(gameTime);
goblinAttackTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (goblinAttackTimer >= goblinAttackDelay)
{
goblinAttackTimer -= goblinAttackDelay;
shortSwordsman.health -= goblinDamage;
if (shortSwordsman.health <= 0)
{
shortList.Remove(shortSwordsman);
}
}
}
}
if (goblinRect.Intersects(background.goodCastleRect))
{
collided = true;
goblinList[i].AnimateAttack(gameTime);
goblinAttackTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (goblinAttackTimer >= goblinAttackDelay)
{
goblinAttackTimer -= goblinAttackDelay;
goodCastleHealth -= goblinDamage;
}
}
if (collided == false)
{
goblinList[i].AnimateWalk(gameTime);
goblinList[i].position.X -= goblinSpeed;
}
}
}
Your collided bool shouldn't be a variable of those classes, as those classes seem to operate on the entire lists of all the entities. Instead the collision detection should happen on an entity by entity basis, basically: make the collided bool a property of goblins and swordsmen. This would mean that you'll have to check for intersections with other creatures of the same type as well, probably without an attack command.
This is the code I am using at the moment - shortswordsman and goblin are the same so i will only show one:
In the goblin class:
public Goblin(Vector2 position, float health, bool Collided, Rectangle goblinRect)
{
this.position = position;
this.health = health;
this.Collided = Collided;
this.goblinRect = goblinRect;
}
In the game1 class:
void CreateGoblin()
{
goblinList.Add(new Goblin(new Vector2(1900, 270), 100, false, new Rectangle()));
}
And then for the collisions i tried this - this includes the bit to try and stop them overlapping each other:
private void GoblinMoveCollisions(GameTime gameTime)
{
int goblinSpeed = 2;
int goblinDamage = 20;
for (int i = 0; i < goblinList.Count; i++)
{
goblinList[i].Collided = false;
goblinList[i].goblinRect = new Rectangle((int)goblinList[i].position.X, (int)goblinList[i].position.Y, Goblin.texture.Width / 4 - 20, Goblin.texture.Height);
List<ShortSwordsman> tempShortList = new List<ShortSwordsman>(shortList);
foreach (ShortSwordsman shortSwordsman in tempShortList)
{
Rectangle shortRect = new Rectangle((int)shortSwordsman.position.X, (int)shortSwordsman.position.Y, ShortSwordsman.texture.Width / 4 - 20, ShortSwordsman.texture.Height);
if (goblinList[i].goblinRect.Intersects(shortRect))
{
goblinList[i].Collided = true;
goblinList[i].AnimateAttack(gameTime);
goblinAttackTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (goblinAttackTimer >= goblinAttackDelay)
{
goblinAttackTimer -= goblinAttackDelay;
shortSwordsman.health -= goblinDamage;
if (shortSwordsman.health <= 0)
{
shortList.Remove(shortSwordsman);
}
}
}
}
if (goblinList[i].goblinRect.Intersects(background.goodCastleRect))
{
goblinList[i].Collided = true;
goblinList[i].AnimateAttack(gameTime);
goblinAttackTimer += (float)gameTime.ElapsedGameTime.TotalSeconds;
if (goblinAttackTimer >= goblinAttackDelay)
{
goblinAttackTimer -= goblinAttackDelay;
goodCastleHealth -= goblinDamage;
}
}
if (goblinList[i].goblinRect.Intersects(goblinList[i].goblinRect))
{
goblinList[i].Collided = true;
goblinList[i].AnimateStill(gameTime);
}
if (goblinList[i].Collided == false)
{
goblinList[i].AnimateWalk(gameTime);
goblinList[i].position.X -= goblinSpeed;
}
}
}