pygame_sdl2 - app is crashing on mobile during pygame.mouse.get_pressed() - android

I am developing a game for android with pygame and pygame_sdl2, and rapt for deploy.
Currently, the game is at a very first stage of development.
I have a joypad draw in the bottom left of my screen, and, when the mouse is pressed in the coordinates of the joypad's buttons, a character is moved according to the button durection. The mouse events are used as touch events as in this (working) example.
The problem is: the game is working on my laptop (I am using Ubuntu), but not on my mobile device. When I start the game, everything shows up as expected, but as soon as I touh the screen (no matter if it's on the buttons or somewhere else), the app goes in background.
My game is in a public github repo if you want to see the whole code (everything relevant is in the main.py file).
I think the error is triggered by the call to pygame.mouse.get_pressed().
Here is some relevant code which hopefully would help in understanding the problem.
Joypad class (btn_pressed method)
def btn_pressed(self, mouse_event):
# check if left mouse is being pressed
if pygame.mouse.get_pressed()[0]:
x, y = mouse_event.pos
if self.btn_up.rect.collidepoint(x, y):
return 'UP'
elif self.btn_down.rect.collidepoint(x, y):
return 'DOWN'
elif self.btn_left.rect.collidepoint(x, y):
return 'LEFT'
elif self.btn_right.rect.collidepoint(x, y):
return 'RIGHT'
Character class (move method)
def move(self, joypad_direction):
"""
move the character
to be used along with Joypad.btn_pressed returns
('UP', 'DOWN' 'LEFT', 'RIGHT')
"""
self.dx = 0
self.dy = 0
# check for horizontal move
if joypad_direction == 'LEFT':
self.dx = -self.speed
self.rect.move_ip(-self.speed, 0)
if joypad_direction == 'RIGHT':
self.dx = +self.speed
self.rect.move_ip(self.speed, 0)
self.dx = 0
# check for vertical move
if joypad_direction == 'UP':
self.dy = -self.speed
self.rect.move_ip(0, -self.speed)
if joypad_direction == 'DOWN':
self.dy = +self.speed
self.rect.move_ip(0, self.speed)
self.dy = 0
main loop
while True:
ev = pygame.event.wait()
# If not sleeping, draw the screen.
if not sleeping:
hero.move(joypad.btn_pressed(ev))
screen.fill((0, 0, 0, 255))
joypad.buttons.draw(screen)
if x is not None:
screen.blit(hero.image, (x, y))
pygame.display.flip()

As explained in the comments, there was an issue in my main loop.
I simply had to change my code from:
if not sleeping:
if not sleeping:
hero.move(joypad.btn_pressed(ev))
to:
if not sleeping:
if ev.type == pygame.MOUSEMOTION or ev.type == pygame.MOUSEBUTTONUP:
hero.move(joypad.btn_pressed(ev))
so that "Joypad class (btn_pressed method)" does not get an error when calling x, y = mouse_event.pos when the event was (e.g.) QUIT, thus not returning any coordinates (see also the image belowe taken from the pygame's event documentation page).

Related

Corona SDK multitouch run and jump

I think this should be very easy to do, but I'm not able to find any solution. It's always just system.enable("multitouch") and then something with setFocus() method.
I have a right button, that responds to touch event and makes player run right when held. Then I have a jump button, that responds to tap event, making player jump.
Running works, jumping works, but when I run and try to jump nothing happens.
Here is some code:
local speed = 3
local motionx = 0
-- When right arrow is touched, move character right
function right:touch()
if string.find(player.sequence,"jump") then
player:setSequence("jumpRight")
motionx = speed;
elseif string.find(player.sequence,"duck") then
player:setSequence("duckRight")
else
player:setSequence("goingRight")
motionx = speed;
end
player:play()
end
right:addEventListener("touch",right)
-- When up arrow is tapped, jump character
function jump:tap()
if not isJumping then
if string.find(player.sequence, "goingRight") then
isJumping = true
player:setSequence("jumpRight")
player:setLinearVelocity(0,-120)
end
if string.find(player.sequence, "goingLeft") then
isJumping = true
player:setSequence("jumpLeft")
player:setLinearVelocity(0,-120)
end
if string.find(player.sequence, "duckLeft") then
player:setSequence("goingLeft")
end
if string.find(player.sequence, "duckRight") then
player:setSequence("goingRight")
end
player:play()
end
end
jump:addEventListener("tap",jump)
-- Move character
local function movePlayer (event)
player.x = player.x + motionx;
end
Runtime:addEventListener("enterFrame", movePlayer)
I don't knowh where, how or why should I use the setFocus() method. But so far when running, I cannot jump until I release the right button.
It was my mistake, that I wanted to use TAP event for jump. I guess since it is called multiTOUCH it only works with multiple TOUCH events :) I changed TAP events to TOUCH events and added:
if event.phase == "began" then
display.getCurrentStage():setFocus( event.target, event.id )
--other code
end
if event.phase == "ended" or event.phase == "cancelled" then
display.getCurrentStage():setFocus( event.target, nil )
end
Now it works nicely.

Unity3d Gyroscope look around

I'm new to Unity and I am trying to build a solar system exploration app through unity. I have the environment set up, and now all I need is the ability to look around (via tilting and moving the phone itself, which is android) smoothly. I have the ability to look around, but if I do a complete 180, it seems to invert the physical orientation of the phone with the visual movements in game, e.g. if I have turn 180 degrees, if I tilt the phone down it shifts my vision in game to the right, up results in visual shift to the left. Here is the code I have thus far:
#pragma strict
private var quatMult : Quaternion;
private var quatMap : Quaternion;
function Start () {
Input.gyro.enabled = true;
}
function Update () {
#if UNITY_ANDROID
quatMap = Input.gyro.attitude;
#endif
transform.localRotation = Quaternion.Euler(90, 0, 0) * quatMap * Quaternion(0,0,1,0) /*quatMult*/;
}
Any help is greatly appreciated. Thanks.
This should be what you're looking for: https://gist.github.com/chanibal/baf46307c4fee3c699d5. Just drag it to the camera and it should work.
You might want to remove the reset on touch part (Input.touchCount > 0 in Update) and debug information (the OnGui method).

Unity3D Android - Move your character to a specific x position

Im making a new game for android and I wanted to move my character (which is a cube for now) to a specific x location (on top of a flying floor/ground thingy) but I've been having some troubles with it.I've been using this script :
var jumpSpeed: float = 3.5;
var distToGround: float;
function Start(){
// get the distance to ground
distToGround = collider.bounds.extents.y;
}
function IsGrounded(): boolean {
return Physics.Raycast(transform.position, -Vector3.up, distToGround + 0.1);
}
function Update () {
// Move the object to the right relative to the camera 1 unit/second.
transform.Translate(Vector3.forward * Time.deltaTime);
if (Input.anyKeyDown && IsGrounded()){
rigidbody.velocity.x = jumpSpeed;
}
}
And this is the result (which is not what I want) :
https://www.youtube.com/watch?v=Fj8B6eI4dbE&feature=youtu.be
Anyone has any idea how to do this ? Im new in unity and scripting.Im using java btw.
Ty.
I may not be understanding your question right, but here is what I think you want.
I think that you want the player to jump straight up, so here is the code for that:
if (Input.anyKeyDown && IsGrounded()) {
rigidbody.AddForce(Vector3.up * jumpSpeed, ForceMode.Impulse);
}
If you do want the player to jump to the right (as is in the video) you can change the "up" in Vector3.up to whatever direction you want (i.e. right, left, down).
If this doesn't help, could you provide some more details on what the desired behavior is?

Corona/Lua and collisions: "attempt to concatenate field 'name' (a nil value)"

I'm trying to get some collision detection working but I can't seem to figure out what the problem is.
The error I'm getting is
...\main.lua:178:attempt to concatenate field 'name' (a nil value)
What I have is this: I have a box (the "ship") that stays at a fixed X coordinate, but moves up and down. It's meant to go through a "tunnel" made up of two rectangles with a gap between them, and I'm trying to detect a collision between the ship and the walls of the tunnel (ie the rectangles).
I get this error when the collision happens. A lot of my code is just modified versions of the official Corona documentation and I'm just not able to figure out what the problem is.
Here are the relevant pieces of code:
function playGame()
-- Display the ship
ship = display.newRect(ship);
shipLayer:insert(ship);
-- Add physics to ship
physics.addBody(ship, {density = 3, bounce = 0.3});
...
beginRun();
end
function beginRun()
...
spawnTunnel(1100); -- this just calls the createTunnel function at a specific location
gameListeners("add");
...
end
function gameListeners(event)
if event == "add" then
ship.collision = onCollision;
ship:addEventListener("collision", ship);
-- repeat above two lines for top
-- and again for bottom
end
end
-- Collision handler
function onCollision(self,event)
if ( event.phase == "began" ) then
-- line 178 is right below this line ----------------------------------
print( self.name .. ": collision began with " .. event.other.name )
end
-- Create a "tunnel" using 2 rectangles
function createTunnel(center, xLoc)
-- Create top and bottom rectangles, both named "box"
top = display.newRect(stuff);
top.name = "wall";
bottom = display.newRect(stuff);
bottom.name = "wall";
-- Add them to the middleLayer group
middleLayer:insert(top);
middleLayer:insert(bottom);
-- Add physics to the rectangles
physics.addBody(top, "static", {bounce = 0.3});
physics.addBody(bottom, "static", {bounce = 0.3});
end
I only get the error message once the two objects should collide, so it seems like the collision is happening, and it is being detected. But for some reason self.name and event.other.name are nil.
Try to use :
top.name = "wall";
and
bottom.name = "wall";
as
top.myName = "wall"
and
bottom.myName = "wall";
Use onCollision function after your "createTunnel: function :
-- Collision handler
function onCollision( self, event)
if ( event.phase == "began" ) then
print( self.myName .. ": collision began with " .. event.other.myName )
end
end
Oh wow. After many hours I finally figured out my stupid, simple mistake.
The problem was that I forgot to give the ship its own name. The code now looks like this and works just fine:
function playGame()
-- Display the ship
ship = display.newRect(ship);
ship.name = "ship"; -- added this line to give the ship a name
shipLayer:insert(ship);
-- Add physics to ship
physics.addBody(ship, {density = 3, bounce = 0.3});
...
beginRun();
end

How do you make an object inactive in Lua (using Corona SDK) after collision?

I am writing in Lua, using the Corona SDK, and I am looking to make an object inactive after a collision.
function onCollision(event)
if event.phase == "began" then
bullet.collided = true
bullet.isVisible = false
bullet:applyLinearImpulse(-5, 0, bullet.x, bullet.y)
explode(event)
end
end
function explode(event)
local x = event.object2.x
local y = event.object2.y
explosion.x = x
explosion.y = y
explosion.isVisible = true
explosion:play()
resetExplosion()
end
The above function takes the single bullet on the screen and makes it invisible after a collision with a ball that it shoots in the y axis. It then applys an impulse to remove it from the screen in the x-axis. My issue is that the ball (object2) in the collision is invisible after collision as well, but it still can be hit by the new bullet. There is only one bullet, so I can directly say bullet.whatever, but there is an array of balls, so the ball has to be addressed like ball[i].whatever.
is there a way to pass the index, i through the onCollision function?
You can set the body to inactive if you use a slight delay in your collision handler.
i.e:
-- Inside your Collision event
local function delay()
--Change the body's active state to false
body.isBodyActive = false
end
timer.performWithDelay( 10, delay )
According to CoronaSDK chapter about event.collision event.object1 and event.object2 are the properties identifying those collided objects (references to the bullet and one of the balls in Your case). So, doesn't it solve Your problem?

Categories

Resources