Remove an object for a short period of time? - object

I have this statement in my Draw method:
public void DrawSprites(GameTime gameTime)
{
spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.AlphaBlend);
if (shieldPowerUp == false)
// Draws the Original ship
player.Draw(gameTime, spriteBatch);
if (playerIsHit == true)
// method Draws a blinking ship for a second
PlayerIsHit(gameTime, spriteBatch);
if (shieldPowerUp == true)
// Draws a ship with a Shield for 5 seconds
playerShield.Draw(gameTime, spriteBatch);
// the rest of the method is left out
}
My problem now is that when a new Ship is drawn it Draws over the top of the prevoius one.
I dont know how to remove the original ship object for a short time while the blinking or shielded Ship object is Drawn. Do you guys have any ideas for how I can proceed ?

It solved, the problem was in my Sprites Image file, not in my code. sorry.

Related

How to write code to show who has won the game

i have made a cannon shooting game for two player, the aim is to break the castle down and then try to land the cannon ball onto the opponent but the problem is idk how to write code to show who has won the game when the game is over and all i know is that the code will need to written in the game over section & I am new to code as well
void CMyGame::OnUpdate()
{
if (m_mode == MODE_SHOOT)
{
/////////////////////////////////////////////////
// this code will only be executed while shooting
// TODO: 1. Add the gravitation
m_ball.Accelerate(0, -8);
// TODO: 2. Check if cannon hit? game over?
if (m_ball.HitTest(m_cannons[1 - m_turn]))
{
GameOver();
}
// TODO: 3. Check if the ball is outside the screen. Test the following cases:
// - ball to the left of the screen
if (m_ball.GetX() < 0)
NextTurn();
// - ball to the right of the screen (screen width = 800)
if (m_ball.GetX() > 800)
NextTurn();
// - ball below the screen
if (m_ball.GetY() < 0)
NextTurn();
// TODO: 4. Check if the ball hit the castle?
for each (CSprite * pSprite in m_castle)
{
if (m_ball.HitTest(pSprite))
NextTurn();
}
}
// Check if the castle has taken damage
for (CSprite* pSprite : m_castle)
{
if (m_ball.HitTest(pSprite))
pSprite->Delete();
}
m_castle.delete_if(deleted);
// Update the ball's position
m_ball.Update(GetTime());
the part i need help on is how to write code that will show who has won the game
// called when Game is Over
void CMyGame::OnGameOver()
{
m_cannons[1 - m_turn]->SetImage("fire");
m_mode = MODE_GAMEOVER;
}
Hard to say without seeing the rest of your code and info on how your game works, but you can follow something like this:
Assuming you can check when a cannon lands somewhere and can track the % hit points of each player (which I believe you can do considering you have gravity planned in your given code):
Write a function which is called each time a cannon ball lands, check if the ball has dealt the final blow on the opponent's character. From what you say, you probably do not need to do this check until the castle has been broken down. So something along the lines of if(!castleBroken) {return;} at the start of the function would only check the opponent's HP if the castle is broken (again, assuming that the opponent can only take damage if the castle is broken). Here, castleBroken is a bool which starts as false and becomes true when the cannon has broken the opponent's castle.
This is a similar idea to a Tic-Tac-Toe game I wrote in the past, where after each move, I would check the board state. If the game was over, the game over screen would be printed with the winner declared, or in some cases, a draw.

LibGDX very strange bug - objects are disappeared

When I was creating my first tiled map creator in libGDX, I noticed a very strange bug. I creating grid of objects like this:
private static final int GRID_WIDTH=2400;
private static final int GRID_HEIGHT=2400;
private static final int CELL_SIZE=60;
so you can see there are 2400/60x2400/60 objects or cells. I am creating my map like this:
private void createMap(){
cells = new Cell[GRID_WIDTH/CELL_SIZE][GRID_HEIGHT/CELL_SIZE];
for(int i=0;i<GRID_WIDTH/CELL_SIZE;++i){
for(int j=0;j<GRID_HEIGHT/CELL_SIZE;++j){
cells[i][j]=new Cell(textures[0],i*CELL_SIZE,j*CELL_SIZE);
}
}
}
I also have coordinates for my debug in the screen so I know where they started to disappear. Y coordinate is ok there are from 0 to 2400, but on the X they started to disappear at 1500. When I start to draw there some texture every column will be visible to that texture for example (when I start to write texture at x=2100 every disappeared column will be visible to 2100) and when I will delete that texture every column will disappear again to 1500. So the objects are there but they are not visible. It is so annoying does anyone know about this bug?
As you can see coordinates are at the bottom left this is at the beginning:
and this is when I will add there some texture
[Edited] Code with camera:
private float x=GRID_WIDTH/2,y=GRID_HEIGHT/2;
#Override
public void render(float delta) {
batch = new SpriteBatch();
camera=new OrthographicCamera(CAM_WIDTH,CAM_HEIGHT);
viewPos = new Vector3();
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
viewPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(viewPos);
batch.begin();
if(Gdx.input.isKeyPressed(Input.Keys.RIGHT) || Gdx.input.isKeyPressed(Input.Keys.D))
x+=SPEED*Gdx.graphics.getDeltaTime();
if(Gdx.input.isKeyPressed(Input.Keys.LEFT) || Gdx.input.isKeyPressed(Input.Keys.A))
x-=SPEED*Gdx.graphics.getDeltaTime();
if(Gdx.input.isKeyPressed(Input.Keys.UP) || Gdx.input.isKeyPressed(Input.Keys.W))
y+=SPEED*Gdx.graphics.getDeltaTime();
if(Gdx.input.isKeyPressed(Input.Keys.DOWN) || Gdx.input.isKeyPressed(Input.Keys.S))
y-=SPEED*Gdx.graphics.getDeltaTime();
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
camera.position.set(x,y,0);
camera.update();
batch.setProjectionMatrix(camera.combined);
batch.end();
}
The camera is correct. The problem is the batch.begin() and batch.end(). As you might know you cannot do batch.begin() and then shaperenderer.begin() directly after each others without closing one of them. Reason for this I am not 100% about. stage works similar. This means we have to close the batch before drawing the stage
batch.end();
stage.draw();
batch.begin();
// draw your batch stuff here
Also it's terrible to do this
batch = new SpriteBatch();
camera=new OrthographicCamera(CAM_WIDTH,CAM_HEIGHT);
inside the render method. Instead, put it into the create() method or some of your own initialize method. The important thing is to not create a new SpriteBatch every frame as the batch isn't collected by the GC. So you have to manually dispose it using batch.dispose() or it will leak so much memory your RAM will be gone in no time.
I hope this helped you out, good luck.

SWT Canvas fails to redraw on Windows but works on Linux

this.canvas = new Canvas(shell, SWT.NO_BACKGROUND);
I'm using a PaintListener:
this.canvas.addPaintListener(new PaintListener() {
#Override
public void paintControl(PaintEvent e) {
// Draw images
synchronized (imageMarks) {
for (ImageMark mark : Whiteboard.this.imageMarks)
{
Image image = Whiteboard.this.getImage(mark.id);
Point position = ScaledPoint.toSWTPoint(Whiteboard.this.getCanvasSize(), mark.getPosition());
Point bounds = mark.getUnscaledBoundaries(Whiteboard.this.getCanvasSize());
e.gc.drawImage(image, 0, 0, image.getBounds().width, image.getBounds().height, position.x, position.y,
bounds.x, bounds.y);
}
}
// Draw pencil marks
synchronized (pencilMarks) {
e.gc.setLineWidth(LINE_WIDTH);
for (double[] line : Whiteboard.this.pencilMarks)
{
Point lastPosPoint = ScaledPoint.toSWTPoint(Whiteboard.this.getCanvasSize(), new ScaledPoint(line[0], line[2]));
Point newPosPoint = ScaledPoint.toSWTPoint(Whiteboard.this.getCanvasSize(), new ScaledPoint(line[1], line[3]));
e.gc.drawLine(lastPosPoint.x, lastPosPoint.y, newPosPoint.x, newPosPoint.y);
}
}
// Draw pointer, assuming it's there
if (pointerMark != null)
{
synchronized (pointerMark) {
Point pos = ScaledPoint.toSWTPoint(Whiteboard.this.getCanvasSize(), pointerMark.getPosition());
if (pointerMark.isFlipped())
e.gc.drawImage(Whiteboard.pointerImageFlipped, pos.x, pos.y);
else
e.gc.drawImage(Whiteboard.pointerImage, pos.x, pos.y);
}
}
}
});
and redrawing the canvas via a canvas.redraw() call. On 64-bit Linux, this seems to be working without any issues, but strangely enough, on 64-bit Windows, nothing ever ends up being erased or redrawn. For example, if the screen is resized, the pencil markings do not resize as well, they just end up being cut out of the screen. When new marks are added (in other words, when the paint listener is called again), the repositioned markings are redrawn on top of the old ones which didn't scale with the window. In other words, I believe the canvas is not being cleared upon canvas.redraw(). Is there a workaround for this?
You are specifying SWT.NO_BACKGROUND which stops the Canvas being cleared before each paint.
If you use SWT.NO_BACKGROUND it is your paint method's responsibility to draw every pixel of the Canvas.
SWT.NO_BACKGROUND JavaDoc:
By default, before a widget paints, the client area is filled with the
current background. When this style is specified, the background is
not filled, and the application is responsible for filling every pixel
of the client area. This style might be used as an alternative to
"double-buffering" in order to reduce flicker. This style does not
mean "transparent" - widgets that are obscured will not draw through.

NSSplitViewItem collapse animation and window setFrame conflicting

I am trying to make a (new in 10.10) NSSplitViewItem collapse and uncollapse whilst moving its containing window so as to keep the whole thing "in place".
The problem is that I am getting a twitch in the animation (as seen here).
The code where I'm doing the collapsing is this:
func togglePanel(panelID: Int) {
if let splitViewItem = self.splitViewItems[panelID] as? NSSplitViewItem {
// Toggle the collapsed state
NSAnimationContext.runAnimationGroup({ context in
// special case for the left panel
if panelID == 0 {
var windowFrame = self.view.window.frame
let panelWidth = splitViewItem.viewController.view.frame.width
if splitViewItem.collapsed {
windowFrame.origin.x -= panelWidth
windowFrame.size.width += panelWidth
} else {
windowFrame.origin.x += panelWidth
windowFrame.size.width -= panelWidth
}
self.view.window.animator().setFrame(windowFrame, display: true)
}
splitViewItem.animator().collapsed = !splitViewItem.collapsed
}, completionHandler: nil)
}
}
I am aware of the "Don't cross the streams" issue (from session 213, WWDC'13) where a window resizing animation running on the main thread and a core animation collapse animation running on a separate thread interfere with each other. Putting the splitViewItem collapse animation onto the main thread seems like the wrong approach and I've got a nagging feeling there's a much better way of doing this that I'm missing.
Since I am not finding any documentation on the NSSplitViewItems anywhere (yet) I would appreciate any insights on this.
I have the little test project on GitHub here if anyone wants a look.
Update The project mentioned has now been updated with the solution.
Thanks,
Teo
The problem is similar to the "don't cross the streams" issue in that there are two drivers to the animation you've created: (1) the split view item (2) the window, and they're not in sync.
In the example from the '13 Cocoa Animations talk, constraints were setup to result in the correct within-window animation as only the window's frame was animated.
Something similar could be tried here -- only animating the window's frame and not the split view item, but since the item manages the constraints used to (un)collapse, the app can't control exactly how within-window content animates:
Instead the split view item animation could completely drive the animation and use NSWindow's -anchorAttributeForOrientation: to describe how the window's frame is affected.
if let splitViewItem = self.splitViewItems[panelID] as? NSSplitViewItem {
let window = self.view.window
if panelID == 0 {
// The Trailing edge of the window is "anchored", alternatively it could be the Right edge
window.setAnchorAttribute(.Trailing, forOrientation:.Horizontal)
}
splitViewItem.animator().collapsed = !splitViewItem.collapsed
}
For anyone using Objective C and targeting 10.11 El Capitan.
This did the trick for me, didn't need to set AnchorAttributes.
splitViewItem.collapsed = YES;

Draw a line in mfc with help of toolbar

I am trying to make a paint application in MFC using visul basic c++ 6.0 i have already created a window using Create function and also have created a toolbar with a tool line but i am stuck on how to code for the line because the function i know goes like d.lineTo(x,y) and d.Moveto(x2,y2) but it comes under the line function how do i use OnLButtonDown to Trap the co-ordiantes or is there any other way i can draw a line ..? any help will be useful
have a look at the MFC Scribble tutorial :
http://msdn.microsoft.com/en-us/library/aa716527%28v=vs.60%29.aspx)
It will get you started on how to handling mouse click and mouse move and drawing.
M.
Ok, you're going to have to override several member functions to do this. I've outlined an approach below. My example below deals with a single line-drawing operation (from mouse down, to mouse up). An exercise for you, is to make it so that once you've done one, you can then do another at a different place. It's easy, btw!
CWnd::OnLButtonDown(UINT _flags, CPoint _pt);
CWnd::OnLButtonUp(UINT _flags, CPoint _pt);
CWnd::OnMouseMove(UINT _flags, CPoint _pt);
CWnd::OnPaint()
Apologies if some of these function signatures are wrong! Add some members to your window class:
// at the top of your file
#include <vector>
// in your class
typedef std::vector<POINT> PointVector;
PointVector m_Points;
CYourWnd::OnLButtonDown(UINT _flags, CPoint _pt);
{
// NOTE: For more than one set of drawing, this will be different!
m_Points.clear();
m_Points.push_back(POINT(_pt.x, _pt.y));
}
CYourWnd::OnMouseMove(UINT _flags, CPoint _pt);
{
if(_flags & MK_LBUTTON)
{
const POINT& last(m_Points.back());
if(_pt.x != last.x || _pt.y != last.y)
{
m_Points.push_back(POINT(_pt.x, _pt.y));
Invalidate();
}
}
}
CYourWnd::OnPaint()
{
CPaintDC dc(this);
CRect rcClient; GetClientRect(&rc);
FillSolidRect(&rcClient, RGB(255, 255, 255));
if(m_Points.size())
{
dc.MoveTo(m_Points[0].x, m_Points[0].y);
for(PointsVector::size_type p(1);
p < m_Points.size();
++p)
dc.LineTo(m_Points[p].x, m_Points[p].y);
}
}
Obviously, this is crude and gives you a single drawing operation. Once you click the left button down again, it erases what you've done. So, once you have this working:
Make it so you can draw an unlimited amount of lines. You could accomplish this in several ways such as an additional container (to store vectors), or even drawing-operation classes that you can store in a single vector and then execute.
This solution may well flicker. How might you stop this? Perhaps OnEraseBkgnd holds the clue...
How about more colours?
All signs point towards creating some drawing-classes that encapsulate this for you, but I hope this has got you started.

Resources