Is the GML debugger showing me values for the wrong object/sprite? - gml

When the player (the_guy_obj) collides with food (berry_obj) and hits enter, the berry plays an "eaten" animation and stops at the last frame.
At the same time, the player plays an "eating" animation, and, upon reaching the last frame, switches to a static sprite. The following is written in their collide events:
(under berry_obj)
hitEnter = keyboard_check_pressed(vk_enter);
if(hitEnter)
{
sprite_index = br_ani;
}
if(image_index == 4)
{
image_speed = 0;
}
(under the_guy_obj)
if (wasHit == true) {
if (lastPressed_L) //checks if facing left
{
sprite_index = eat_left;
}
if (lastPressed_R) //checks if facing right
{
sprite_index = eat_right;
}
if (lastPressed_D) //checks if facing down
{
sprite_index = down_eat;
}
if (lastPressed_U) //checks if facing up
{
sprite_index = up_eat;
}
}
While I'm debugging, "sprite_index" and "image_speed" return the same values in both collision events.
In the actual game, it works just fine, each object changes to the sprite I set it to.
What's going on? Is it reading these values as the same? Is it switching back and forth when different events are triggered?

If I recall correctly: sprite_index returns the ID of the sprite, and image_index returns the frame of the current sprite. where image_speed returns the value you've set at the image sprite on how much interval is inbetween the sprites.
Perhaps by coincidence, the numbers you were comparing matched each other?

Related

How do I prevent touches from hitting hidden content in SKCropNode?

I'm making pretty heavy use of SKCropNode in my game both for stylistic uses and also in one case where I've built my own SpriteKit version of UIScrollView. I've noticed that when I get a touch event or when a gesture recognizer fires at a certain point, SKScene.nodeAtPoint(...) is still hitting nodes that are hidden at the touch point from the crop node.
How do I prevent SKScene.nodeAtPoint(...) from hitting cropped content, and instead return the next visible node beneath it?
You can't. Everything is based on the frame of the content, and with crop nodes, it is huge. The only thing you can do is check the point of touch, use nodesAtPoint to get all nodes, then enumerate one by one, checking whether or not the touch point is touching a visible pixel by either checking the pixel data, or having a CGPath outlining of your sprite and checking if you are inside that.
I managed to work my way around this one, but it isn't pretty and it doesn't work in every scenario.
The idea is, when a touch is recorded, I iterate over all nodes at that point. If any of those nodes are (or are children of) SKCropNodes, I check the frame of the mask on the crop node. If the touch lies outside the mask, we know the node is not visible at that point and we can assume the touch didn't hit it.
The issue with this method is that I don't do any evaluation of transparency within the crop mask - I just assume it's a rectangle. If the mask is an abnormal shape, I may give false positives on node touches.
extension SKScene {
// Get the node at a given point, but ignore those that are hidden due to SKCropNodes.
func getVisibleNodeAtPoint(point: CGPoint) -> SKNode? {
var testedNodes = Set<SKNode>()
// Iterate over all the nodes hit by this click.
for touchedNode in self.nodesAtPoint(point) {
// If we've already checked this node, skip it. This happens because nodesAtPoint
// returns both leaf and ancestor nodes, and we test the ancestor nodes while
// testing leaf nodes.
if testedNodes.contains(touchedNode) {
continue
}
var stillVisible = true
// Walk the ancestry chain of the target node starting with the touched
// node itself.
var currentNode: SKNode = touchedNode
while true {
testedNodes.insert(currentNode)
if let currentCropNode = currentNode as? SKCropNode {
if let currentCropNodeMask = currentCropNode.maskNode {
let pointNormalizedToCurrentNode = self.convertPoint(point, toNode: currentCropNode)
let currentCropNodeMaskFrame = currentCropNodeMask.frame
// Check if the touch is inside the crop node's mask. If not, we
// know we've touched a hidden point.
if
pointNormalizedToCurrentNode.x < 0 || pointNormalizedToCurrentNode.x > currentCropNodeMaskFrame.size.width ||
pointNormalizedToCurrentNode.y < 0 || pointNormalizedToCurrentNode.y > currentCropNodeMaskFrame.size.height
{
stillVisible = false
break
}
}
}
// Move to next parent.
if let parent = currentNode.parent {
currentNode = parent
} else {
break
}
}
if !stillVisible {
continue
}
// We made it through the ancestry nodes. This node must be visible.
return touchedNode
}
// No visible nodes found at this point.
return nil
}
}

flash cc createjs hittest works without hit

the rect should be alpha=0.1 once the circle touches the rect . but if statement not working . it becomes 0.1 opacity without hitting
/* js
var circle = new lib.mycircle();
stage.addChild(circle);
var rect = new lib.myrect();
stage.addChild(rect);
rect.x=200;
rect.y=300;
circle.addEventListener('mousedown', downF);
function downF(e) {
stage.addEventListener('stagemousemove', moveF);
stage.addEventListener('stagemouseup', upF);
};
function upF(e) {
stage.removeAllEventListeners();
}
function moveF(e) {
circle.x = stage.mouseX;
circle.y = stage.mouseY;
}
if(circle.hitTest(rect))
{
rect.alpha = 0.1;
}
stage.update();
*/
The way you have used hitTest is incorrect. The hitTest method does not check object to object. It takes an x and y coordinate, and determines if that point in its own coordinate system has a filled pixel.
I modified your example to make it more correct, though it doesn't actually do what you are expecting:
circle.addEventListener('pressmove', moveF);
function moveF(e) {
circle.x = stage.mouseX;
circle.y = stage.mouseY;
if (rect.hitTest(circle.x, circle.y)) {
rect.alpha = 0.1;
} else {
rect.alpha = 1;
}
stage.update();
}
Key points:
Reintroduced the pressmove. It works fine.
Moved the circle update above the hitTest check. Otherwise you are checking where it was last time
Moved the stage update to last. It should be the last thing you update. Note however that you can remove it completely, because you have a Ticker listener on the stage in your HTML file, which constantly updates the stage.
Added the else statement to turn the alpha back to 1 if the hitTest fails.
Then, the most important point is that I changed the hitTest to be on the rectangle instead. This essentially says: "Is there a filled pixel at the supplied x and y position inside the rectangle?" Since the rectangle bounds are -49.4, -37.9, 99, 76, this will be true when the circle's coordinates are within those ranges - which is just when it is at the top left of the canvas. If you replace your code with mine, you can see this behaviour.
So, to get it working more like you want, you can do a few things.
Transform your coordinates. Use localToGlobal, or just cheat and use localToLocal. This takes [0,0] in the circle, and converts that coordinate to the rectangle's coordinate space.
Example:
var p = rect.localToLocal(0, 0, circle);
if (rect.hitTest(p.x, p.y)) {
rect.alpha = 0.1;
} else {
rect.alpha = 1;
}
Don't use hitTest. Use getObjectsUnderPoint, pass the circle's x/y coordinate, and check if the rectangle is in the returned list.
Hope that helps. As I mentioned in a comment above, you can not do full shape collision, just point collision (a single point on an object).

LibGdx Input Handling and Collision Detection

I'm playing with libGdx, creating a simple platformer game. I'm using Tiled to create the map and the LibGdx tiledMap renderer.
It's a similar setup to the SuperKoalio libgdx example.
My Collision detection at the moment, it just determining whether the player has hit a tile to the right of it, above it or below it. When it detects a collision to the right, it sets the players state to standing.
Control of the player is done through the InputHandler. When the D key is pressed, it sets the players state to walking, when the key is released, it sets the state to standing.
My problem is, that if I'm holding down D, and I jump and hit a platform and stop, even when the player has dropped back down and should be able to continue moving, it won't, not until I release the D key and press it again. I can jump fine, but not walk.
Any ideas on why this is and how I can fix it? I've been staring at it for so long that I might be missing something obvious, in which case a fresh pair of eyes might help.
This is the code I've got right at the start of my player.update function to get the player moving.
if(state == State.Standing) {
velocity.x = 0;
} else if(state == State.Walking || state == State.Jumping) {
velocity.x = MAX_VELOCITY;
}
And this is an extract of the collision code :
for (Rectangle tile : tiles) {
if (playerRect.overlaps(tile)) {
state = State.Standing;
break;
}
}
Originally, the collision response set x velocity to 0, and the velocity was used to determine the state, which still produced the same problem.
Thanks
As your Collision-detection is allready working, the thing you need to change is the collision handling.
You set the Players state to Standing.
Instead of doing this you culd set a flag collision and in the update check this flag:
if(state == State.Standing || collision) {
velocity.x = 0;
} else if(state == State.Walking || state == State.Jumping) {
velocity.x = MAX_VELOCITY;
}
This way you know, if you don't move becuase you can't (collision==true) or if you don't move, because you don't press the key (state != State.Standing)
Of course you also need to know, when you don't collide anymore.
For this you could reset the collision flag after setting the velocity and recalculate it the next frame.

SDL2 window resize mouse position

How do i make so that positions adapts to the new window position when i resize my window in SDL2 and with SDL_RenderSetLogicalSize?
I want to be able to hover a text and make it change color but whenever i resize the window its still in the same window cords. Is there a way to adapt the mouse?
void MainMenu::CheckHover()
{
for (std::list<MenuItem>::iterator it = menuItems.begin(); it != menuItems.end(); it++)
{
Text* text = (*it).text;
float Left = text->GetX();
float Right = text->GetX() + text->GetWidth();
float Top = text->GetY();
float Bottom = text->GetY() + text->GetHeight();
if (mouseX < Left ||
mouseX > Right ||
mouseY < Top ||
mouseY > Bottom)
{
//hover = false
text->SetTextColor(255, 255, 255);
}
else
{
//hover = true
text->SetTextColor(100, 100, 100);
}
}
}
I had a similar problem some time ago, and it was due to multiple updates of my mouse position in one SDL eventloop. I wanted to move a SDL_Texture around by dragging with the mouse but it failed after resizing, because somehow the mouse coordinates were messed up.
What I did was rearrange my code to have only one event handling the mouse position update. Also I'm not using any calls to SDL_SetWindowSize(). When the user resizes the window the renderer is resized appropriately due to SDL_RenderSetLogicalSize().
The relevant code parts look like this - some stuff is adapted to your case. I would also suggest to use a SDL_Rect to detect if the mouse is inside your text area, because the SDL_Rects will be resized internally if the the window/renderer changes size.
//Declarations
//...
SDL_Point mousePosRunning;
// Picture in picture texture I wanted to move
SDL_Rect pipRect;
// Init resizable sdl window
window = SDL_CreateWindow(
"Window",
SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex),
SDL_WINDOWPOS_CENTERED_DISPLAY(displayIndex),
defaultW, defaultH,
SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE );
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"); // This one is optional
SDL_RenderSetLogicalSize(renderer, defaultW, defaultH);
// SDL main loop
while(SDL_PollEvent(&event) && running)
{
switch (event.type)
{
// Some event handling here
// ...
// Handle mouse motion event
case SDL_MOUSEMOTION:
// Update mouse pos
mousePosRunning.x = event.button.x;
mousePosRunning.y = event.button.y;
// Check if mouse is inside the pip region
if (SDL_EnclosePoints(&mousePosRunning, 1, &pipRect, NULL))
{
// Mouse is inside the pipRect
// do some stuff... i.e. change color
}
else
{
// Mouse left rectangle
}
break;
}
}

Add boundaries to an SKScene

I'm trying to write a basic game using Apple's Sprite Kit framework. So far, I have a ship flying around the screen, using SKPhysicsBody. I want to keep the ship from flying off the screen, so I edited my update method to make the ship's velocity zero. This works most of the time, but every now and then, the ship will fly off the screen.
Here's my update method.
// const int X_MIN = 60;
// const int X_MAX = 853;
// const int Y_MAX = 660;
// const int Y_MIN = 60;
// const float SHIP_SPEED = 50.0;
- (void)update:(CFTimeInterval)currentTime {
if (self.keysPressed & DOWN_ARROW_PRESSED) {
if (self.ship.position.y > Y_MIN) {
[self.ship.physicsBody applyForce:CGVectorMake(0, -SHIP_SPEED)];
} else {
self.ship.physicsBody.velocity = CGVectorMake(self.ship.physicsBody.velocity.dx, 0);
}
}
if (self.keysPressed & UP_ARROW_PRESSED) {
if (self.ship.position.y < Y_MAX) {
[self.ship.physicsBody applyForce:CGVectorMake(0, SHIP_SPEED)];
} else {
self.ship.physicsBody.velocity = CGVectorMake(self.ship.physicsBody.velocity.dx, 0);
}
}
if (self.keysPressed & RIGHT_ARROW_PRESSED) {
if (self.ship.position.x < X_MAX) {
[self.ship.physicsBody applyForce:CGVectorMake(SHIP_SPEED, 0)];
} else {
self.ship.physicsBody.velocity = CGVectorMake(0, self.ship.physicsBody.velocity.dy);
}
}
if (self.keysPressed & LEFT_ARROW_PRESSED) {
if (self.ship.position.x > X_MIN) {
[self.ship.physicsBody applyForce:CGVectorMake(-SHIP_SPEED, 0)];
} else {
self.ship.physicsBody.velocity = CGVectorMake(0, self.ship.physicsBody.velocity.dy);
}
}
}
At first, I used applyImpulse in didBeginContact to push the ship back. This made the ship bounce, but I don't want the ship to bounce. I just want it to stop at the edge.
What is the right way to make the ship stop once it reaches the edge? The code above works most of the time, but every now and then the ship shoots off screen. This is for OS X—not iOS—in case that matters.
Check out this link...
iOS7 SKScene how to make a sprite bounce off the edge of the screen?
[self setPhysicsBody:[SKPhysicsBody bodyWithEdgeLoopFromRect:self.frame]]; //Physics body of Scene
This should set up a barrier around the edge of your scene.
EDIT:
This example project from Apple might also be useful
https://developer.apple.com/library/mac/samplecode/SpriteKit_Physics_Collisions/Introduction/Intro.html
Your code is not clear in what the velocity variables represent. Keep in mind that if the velocity is too high your ship will have travelled multiple points between updates. For example, your ship's X/Y is at (500,500) at the current update. Given a high enough velocity, your ship could be at (500,700) at the very next update. If you had your boundary set at (500,650) your ship would already be past it.
I suggest you do a max check on velocity BEFORE applying it to your ship. This should avoid the problem I outlined above.
As for bouncy, bouncy... did you try setting your ship's self.physicsBody.restitution = 0; ? The restitution is the bounciness of the physics body. If you use your own screen boundaries, then I would recommend setting those to restitution = 0 as well.
Your best bet would be to add a rectangle physics body around the screen (boundary). Set the collision and contact categories of the boundary and player to interact with each other. In the didBeginContact method you can check if the bodies have touched and, if they have, you can call a method to redirect the ship.
Your problem is that your update method may not be checking the location frequently enough before the ship gets off screen.
This will help you to define you screen edges in Swift.
self.physicsBody = SKPhysicsBody ( edgeLoopFromRect: self.frame )