How can I ensure the missile stays on the screen when non-spacebar keys are pressed? - processing

I need to write a Processing program so that "When the user presses the space key a missile is fired from the front of the ship and moves rightwards until leaving the screen. The user can't fire another missile until the first is off the screen."
What I have written doesn't allow the missile to stay on the screen if other keys are pressed. I have tried adding the function under void keyPressed() with boolean true/false statements which only stopped the whole program from working.
How can I make sure it stays on the page? Also, how can I make sure the player can't shoot another missile until their previous one moves off the screen?
This is the code I have:
//global
int ship_y;
int angle;
int missileX;
void setup(){
size(500, 500);
ship_y = 10;
missileX = 55;
}
void draw(){
background(175);
fill(50);
rectMode(CENTER);
rect(30, ship_y, 50, 25);
//missile moves rightwards after spacebar is pressed
if (key == ' '){
circle(missileX, ship_y, 25);
missileX = missileX + 1;
}
}
//ship moves down when 's' is pressed and up when 'w' is pressed
void keyPressed(){
if (key == 's'){
ship_y = ship_y + 2;
}
if (key == 'w'){
ship_y = ship_y - 2;
}
}

Code within the draw() function runs every frame.
So every frame, you're clearing the background, drawing the ship, and drawing the missile. Good.
But.
You put the missile drawing code inside this if statement:
if (key == ' '){
that only draws the missile if the most recent key pressed was space. So as soon as you you press a different key, key is no longer equal to space and your missile doesn't get drawn.
One way to fix it would be to create a variable to indicate whether or not the missile was fired, and use that to determine whether or not to draw the missile (instead of checking the key variable).
Like this:
if (missileFired == true){
circle(missileX, ship_y, 25);
missileX = missileX + 1;
}
Code inside the keyPressed() function only runs once each time a key is pressed. This would be a better place to detect when the spacebar is pressed and turn on the missileFired flag:
void keyPressed(){
// code for other keypresses...
if(key == ' '){
missileFired = true;
}
}
To detect when the missile goes off screen, you'll just need to check whether missileX is greater than the width of the window. draw() would be a good place for that, since you probably want to check for it every time the missile moves.
When missileX gets larger than the window width, you can reset missileFired to false so a new missile can be fired. You'll also need to reset missileX to its original position so it originates from the ship position.

Related

Squashed Sprite when turning horizontally

Unsquashed Sprite Squashed Sprite
My brother has issues with his sprite squashing whilst moving horizontally. The squashing is permanent after moving. I have found the line that causes the problem but cannot figure out what is causing this issue. When I remove this line the squashing stops however the sprite does not turn. He is following Shaun Spalding's Complete Platformer Tutorial and though I've watched it over I cannot find any issues with the actual code.
/// #description Insert description here
// You can write your code in this editor
// get player input
key_left=keyboard_check(vk_left);
key_right=keyboard_check(vk_right);
key_jump=keyboard_check_pressed(vk_up);
// calculate movement
var move=key_right-key_left;
hsp=move*walksp;
vsp=vsp+grv;
if(place_meeting(x,y+1,o_wall)) and (key_jump)
{
vsp=-7;
}
// horizontal collision
if (place_meeting(x+hsp,y,o_wall))
{
while(!place_meeting(x+sign(hsp),y,o_wall))
{
x=x+sign(hsp);
}
hsp=0;
}
x=x+hsp;
// vertical collision
if (place_meeting(x,y+vsp,o_wall))
{
while(!place_meeting(x,y+sign(vsp),o_wall))
{
y=y+sign(vsp);
}
vsp=0;
}
y=y+vsp;
// animation
if(!place_meeting(x,y+1,o_wall))
{
sprite_index=splayerA;
image_speed=0;
if (sign(vsp) > 0) image_index = 1; else image_index = 0;
}
else
{
image_speed=1;
if (hsp==0)
{
sprite_index=s_player;
}
else
{
sprite_index=splayerR;
}
}
if (hsp != 0) image_xscale = sign(hsp); //this line is wrong and causes the squishing
A possible cause of this is that you've set the image_xscale to a different value before using the line:
if (hsp != 0) image_xscale = sign(hsp);
For example, you may have set this in the Create Event to enlarge the sprite:
image_xscale = 2;
But that value is reset after setting image_xscale again, as that line will only return -1 or 1 because of the Sign().
One quick solution is to apply the scale change to that line of code, like this:
if (hsp != 0) image_xscale = 2 * sign(hsp);
(Once again, presuming you've changed it's scale value somewhere else)
Though another solution is to enlarge the sprite itself in the sprite editor, so the scale doesn't have to be kept in mind everytime.

Unity show pop up if the player doesn't move for 5 seconds

I have a task on Unity 3d that if the player doesn't move for 5 seconds, a pop-up shows on the center of the screen and if the player moves, the pop-up disappears. How can I write the logic for this task please ?
Thanks
Here is code that will check the mouse position of the user and see if it has moved in the last 5 seconds. If it has not, then the popup window will show up. If it's hard to read here with the comments (I kind of think it is) copy and paste this code into Visual Studio so the colors will help distinguish code from comments.
[SerializeField] GameObject popupWindow = null;
float totTime;
float timeBeforePause = 5f;
Vector3 updatedMousePosition;
private void Update()
{
// Add the time delta between frames to the totTime var
totTime += Time.deltaTime;
// Check to see if the current mouse position input is equivalent to updateMousePosition from the previous update
// If they are equivalent, this means that the user hasn't moved the mouse
if (Input.mousePosition == updatedMousePosition)
{
// Since the user hasn't moved the mouse, check to see if the total Time is greater than the timeBeforePause
if (totTime >= timeBeforePause)
{
// Set the popup window to true in order to show the window (instantiate instead it if if doesn't exist already)
popupWindow.SetActive(true);
}
}
// If the user has moved the mouse, set the totTime back to 0 in order to restart the totTime tracking variable
else
{
totTime = 0;
}
// Check to see if the popup window is visible (active)
if (popupWindow.activeSelf == true)
{
// Check to see if the user has pressed the Esc button
if (Input.GetKeyDown(KeyCode.Escape))
{
// Hide the window
popupWindow.SetActive(false);
}
}
// Update the updatedMousePosition before the next frame/update loop executes
updatedMousePosition = Input.mousePosition;
}
If you want to track different user input (key presses) you can use a similar method. Also you will have to implement some sort of button on the popup window that will allow the user to exit out from the popup window once they return. Hope this helps!

My program appears to stop working

I am quite new to programming and decided to make a little game, so far I have only made a small block that is able to move in all 4 directions (left, right, up and down). Pretty simple and nothing extra-ordinary. However, when I run my program, sometimes it will stop working, not as in crashing causing Processing itself to crash, but my program will just end.
As far as my testing goes, I think this happens when I press two keys at the same time (like W and S). Does anyone happen to know what causes it to stop, and perhaps how to fix it as well?
void setup(){
size(1080,720);
frameRate(30);
}
int shipLR = 0; //Variable for the ship to go left/right
int shipUD = 0; //Variable for the ship to go up / down
void draw(){
background(0);
shipLR = constrain(shipLR, 0, 1040); //Constrain the ship in the window
shipUD = constrain(shipUD,0,680); // Constrain the ship in the window
move();
Shuttle();
}
void Shuttle(){
rect(shipLR, shipUD, 40,40); //Draw the ship
}
void move(){
if (keyPressed) {
if (key == 'a') {
shipLR = shipLR - 20; // Go left
return;}
if (key == 'd') {
shipLR = shipLR + 20; // Go right
return;}
if (key == 'w'){
shipUD = shipUD - 20; // Go up
return;}
if (key == 's') {
shipUD = shipUD + 20; // Go down
return;}
}
}
Any help will be greatly appreciated.
Edit: I found something that causes this problem to occur more frequent; If I implement a frameRate of a value lower than 60 (currently trying with 30) this happens more often.
Edit 2: With the suggestions below of making my move function in a single if block had a lot of good impact. The program no longer stops when I move the ship in the middle of the window it no longer stops, it now only does it at rare occasions when I bump too often against the borders of the window. Perhaps it has something to do with constrain?
in move() (java naming conventions specify that method names start with lower case) you should exit on the first key pressed found. the code can be re-organized to reduce multiple identical conditions:
void move(){
if (keyPressed) {
if (key == 'a') {
shipLR = shipLR - 20; // Go left
return;
}
if (key == 'd') { // still inside if keyPressed
shipLR = shipLR + 20; // Go right
return;
}
if (key == 'w') {
...
}
} // end of if keyPressed
}
My guess it that the program doesn't "stop working" or end- it's just that your rectangle stops moving. If you let go of all the keys, then push just one key, I'd bet that the rectangle starts moving again. (In the future, please try to be more specific- saying "it stops working" isn't very helpful.)
Anyway, that's because of the way you're handling the key presses. What happens if you press a key other than the ones you're checking for?
You'll enter the move() function, and you'll enter the if(keyPressed) block, but you won't enter any if the other if statements inside that block. The key variable only holds the most recently pressed key.
Depending on what you want to do, you should either refactor those if statements to only change the direction if the key was valid, and to ignore all other key presses. Or you might want to use a set of boolean variables to track multiple keys being pressed at the same time. More info on that approach can be found here.
If you still can't get it working, then please try to be more specific about exactly what happens.

How to write KeyBindings

I am developing a Java 2D Game, in which I have used a KeyListener, but as you probably can guess, it has focusing issues, mainly when the Player is running and you keep the same key pressed for long, for example pressing "W" to run forward, but after some seconds of keep pressing W, the KeyListener dies and no key works, I want to use KeyBindings, as most people suggest it for game development, but I cannot find any usefull tutorials, most of them use some form of Buttons, and other useless features for my game, so how can i avoid the KeyListener from losing focus, or how can I write a simple KeyBinding code, that only moves the player, and other simple stuff used in a game.
This is the kind of Key Binding that I want, I KNOW IT DOES NOT WORK, it is an example:
component.getInputMap().put(KeyStroke.getKeyStroke(VK_W),
"move forward")
component.getActionMap().put("released",
releasedAction);
if(releasedAction == true){
Player.playerSpeedY = 7;
} else{
Player.playerSpeedY = 0;
}
FWI: this is the current KeyListener code:
if(HUD.PlayerHealth > 0){
if(key == KeyEvent.VK_W) {Player.playerSpeedY = -5; keyDown[0]= true;}
if(key == KeyEvent.VK_S) {Player.playerSpeedY = 5; keyDown [1]= true;}
if(key == KeyEvent.VK_A) {Player.playerSpeedX = -5; keyDown [2]= true;}
if(key == KeyEvent.VK_D) {Player.playerSpeedX = 5; keyDown [3]= true;}
}
I keep looking for Actions and Input maps tutorials, or KeyBinding ones, and I just don't find anything useful, another dough, the component in action and input map, what is it for?, should my entire code be based on that, and is there any way to only make the action map move the player, and only that?
Try something like this:
this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0, false), "right");
this.getActionMap().put("right", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
//Do Something Here
Player.playerSpeedX = 5;
}
});
How to use KeyBindings

TranslateTransition jumps over a few pixels

When i click and the animation begins, the image jumps from point A a quarter of the distance it should go and then runs just fine untill it reaches point B does anyone know why?
This is my methot i use for the image movement:
public void sky(Node node, double xDest, double yDest) {
TranslateTransition tTrans = new TranslateTransition(
Duration.seconds(4), node);
// tTrans.setFromX(xPlec);
tTrans.setToX(xDest);
tTrans.setRate(2);
tTrans.setInterpolator(Interpolator.LINEAR);
// tTrans.setFromY(yPlec);
tTrans.setToY(yDest);
tTrans.setRate(2);
tTrans.setInterpolator(Interpolator.LINEAR);
node.setLayoutX(node.getLayoutX() + xDest);
node.setLayoutY(node.getLayoutY() + yDest);
tTrans.play();
}
Why do you set end point for you node before starting transition? Try next code:
tTrans.setFromX(node.getLayoutX());
tTrans.setToX(xDest);
tTrans.setRate(2);
tTrans.setInterpolator(Interpolator.LINEAR);
tTrans.setFromY(node.getLayoutX());
tTrans.setToY(yDest);
tTrans.play();
Also note you don't need to call setRate and setInterpolator two times.

Resources