So I'm making a zombie shooter game that works well, but after running for a while I get hit with this exception:
Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException:
Couldn't load file: 1zom3.png
at com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:140)
at com.badlogic.gdx.graphics.TextureData$Factory.loadFromFile(TextureData.java:98)
at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:100)
at com.badlogic.gdx.graphics.Texture.<init>(Texture.java:92)
at com.lastride.game.Entity.changeState(Entity.java:51)
at com.lastride.game.Enemy.seek(Enemy.java:39)
at com.lastride.game.LastRideGame.update(LastRideGame.java:149)
at com.lastride.game.LastRideGame.render(LastRideGame.java:229)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:215)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
Caused by: java.io.IOException: Error loading pixmap:
at com.badlogic.gdx.graphics.g2d.Gdx2DPixmap.<init>(Gdx2DPixmap.java:57)
at com.badlogic.gdx.graphics.Pixmap.<init>(Pixmap.java:138)
... 9 more
I know for a fact that the image is there as it works, but it seems that after running for a bit it crashes.
This is the method where it crashes on:
public void changeState(int i)
{
//changes the state and concurrently the image associated with the given state
state = i;
sprite = new Sprite(new Texture(Gdx.files.internal(name+i+suff)));//crashes here
bounding = (sprite.getBoundingRectangle());
if (sprite.getTexture().getTextureData().isPrepared()==false)
{
sprite.getTexture().getTextureData().prepare();
}
playerMap = sprite.getTexture().getTextureData().consumePixmap();
}
As #Tenfour04 points out, it could be an out-of-memory problem.
Instead of doing this:
sprite = new Sprite(new Texture(Gdx.files.internal(name+i+suff)));
Create an global (and/or possible static and/or possible final) Texture object, and load it just once at the beginning of your game and use it repeatably.
Something like this:
public static Texture myTexture_1; //<< your texture
public static final int ID_MY_TEXTURE_1 = 1; //<< this will work as an ID
// This method is called once in your game (like in the create() method)...
public static void load() {
myTexture_1 = new Texture(Gdx.files.internal(name + ID_MY_TEXTURE_1 + suff));
}
// when no longer necessary, remove it...
public static void dispose() {
myTexture_1.dispose();
// and so on...
}
then, in your changeState() method, do a switch to retrieve the correct texture:
public void changeState(int i) {
state = i;
switch(i){
case ID_MY_TEXTURE_1 :
sprite = new Sprite(myTexture_1);
break;
// rest of cases...
}
// rest of your code...
}
Related
Please excuse me I'm a complete novice at all this but I'm trying to make a game following "Brackeys How To Make A Video Game" I'm on video 8 if that helps. I can't seem to find what i have done wrong i have added my scripts for "player movement", "player collision" and "game manager". Please if there is anything else you need to help me please ask i really don't want to give up just yet was really enjoying doing this.
Thank you all
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
// This is a reference to the Rigidbody component called "rb"
public Rigidbody rb;
public float forwardForce = 2000f; // Variable that determines the forward force
public float sidewaysForce = 500f; // Variable that determines the sideways force
// We marked this as "Fixed"Update because we
// are using it to mess with physics.
void FixedUpdate ()
{
// Add a forward force
rb.AddForce(0, 0, forwardForce * Time.deltaTime);
if (Input.GetKey("d")) // If the player is pressing the "d" key
{
// Add a force to the right
rb.AddForce(sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (Input.GetKey("a")) // If the player is pressing the "a" key
{
// Add a force to the left
rb.AddForce(-sidewaysForce * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
if (rb.position.y < -1f)
{
FindObjectOfType<GameManager>().EndGame();
}
}
}
using UnityEngine;
public class PlayerCollision : MonoBehaviour {
public PlayerMovement movement; // A reference to our PlayerMovement script
// This function runs when we hit another object.
// We get information about the collision and call it "collisionInfo".
void OnCollisionEnter (Collision collisionInfo)
{
// We check if the object we collided with has a tag called "Obstacle".
if (collisionInfo.collider.tag == "Obstacle")
{
movement.enabled = false; // Disable the players movement.
FindObjectOfType<GameManager>().EndGame();
}
}
}
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour {
bool gameHasEnded = false;
public float restartDelay = 1f;
public GameObject completeLevelUI;
public void CompleteLevel ()
{
completeLevelUI.SetActive(true);
}
public void EndGame ()
{
if (gameHasEnded == false)
{
gameHasEnded = true;
Debug.Log("GAME OVER");
Invoke("Restart", restartDelay);
}
}
void Restart ()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
}
when i fall off ground:
NullReferenceException: Object reference not set to an instance of an object
PlayerMovement.FixedUpdate () (at Assets/Scripts/PlayerMovement.cs:32)
when i hit an obstacle:
NullReferenceException: Object reference not set to an instance of an object
PlayerCollision.OnCollisionEnter (UnityEngine.Collision collisionInfo) (at Assets/Scripts/PlayerCollision.cs:15)
It seems to me that FindObjectOfType<GameManager>() is returning null, which is causing a null reference exception when you attempt to call the EndGame function. This most likely means that there is no object in your scene with the GameManager component on it. The solution to this problem is simple:
Create an empty object in your scene and add the GameManager component to it. This will fix the error in this instance, but it could happen in the future if you're not careful. It is also a good idea to check if you found an object or not before calling functions on it:
GameManager gm = FindObjectOfType<GameManager>();
if (gm != null)
{
gm.EndGame();
}
I'm trying to instantiate a UI image in unity 5 to display a players health. I've used a for loop to spawn a new health block image for every 10 health the player has remaining. However, I can't get the image to actually show on screen (it works when I set up the prefab, but as soon as I try to instantiate it through the code it vanishes). The code isn't finished yet as at the moment I understand all the images will stack on top of each other rather than in a row (which will be the finished result) but I want to make sure I can get the images to actually show first before taking this further. Any help would be appreciated!
Things to know:
Player health is set to 100,
Health per icon is set to 10,
I'm using a prefab (health that only contains a UI image component within my canvas.
code:
using UnityEngine.UI;
public class GameController : MonoBehaviour {
public GameObject player;
public int playerStartingHealth;
public Image healthBarGreen;
public int healthPerIcon;
void Start () {
score = 0;
UpdateScore ();
AddPlayerHealth (playerStartingHealth / healthPerIcon);
StartCoroutine (spawnWaves ());
}
public void AddPlayerHealth (int n) {
for (int i =0; i < n; i++) {
Instantiate(healthBarGreen.gameObject);
}
}
}
Bit of a necro, but this post is high on a google search on the subject. Solution:
Image newImage = Instantiate(prefabImage, Vector3.zero, Quaternion.identity);
newImage.transform.SetParent(canvas.transform, false);
newImage.rectTransform.anchoredPosition = Vector3.zero; // your new position here
I'm trying to follow the tutorial about Watchfaces creation, but I'm stuck.
I copied the code from the wiki so there shouldn't be any error whatsoever, but I'm getting this error while compiling
error: implicit declaration of function 'PBL_IF_ROUND_ELSE' [-Werror=implicit-function-declaration]
I tried to google it but I couldn't find anything useful.
This is the code
#include <pebble.h>
static Window *s_main_window;
static TextLayer *s_time_layer;
static void update_time() {
// Get a tm structure
time_t temp = time(NULL);
struct tm *tick_time = localtime(&temp);
// Write the current hours and minutes into a buffer
static char s_buffer[8];
strftime(s_buffer, sizeof(s_buffer), clock_is_24h_style() ? "%H:%M" : "%I:%M", tick_time);
// Display this time on the TextLayer
text_layer_set_text(s_time_layer, s_buffer);
}
static void tick_handler(struct tm *tick_time, TimeUnits units_changed) {
update_time();
}
static void main_window_load(Window *window) {
// Get information about the Window
Layer *window_layer = window_get_root_layer(window);
GRect bounds = layer_get_bounds(window_layer);
// Create the TextLayer with specific bounds
s_time_layer = text_layer_create(
GRect(0, PBL_IF_ROUND_ELSE(58, 52), bounds.size.w, 50));
// Improve the layout to be more like a watchface
text_layer_set_background_color(s_time_layer, GColorClear);
text_layer_set_text_color(s_time_layer, GColorBlack);
text_layer_set_text(s_time_layer, "00:00");
text_layer_set_font(s_time_layer, fonts_get_system_font(FONT_KEY_BITHAM_42_BOLD));
text_layer_set_text_alignment(s_time_layer, GTextAlignmentCenter);
// Add it as a child layer to the Window's root layer
layer_add_child(window_layer, text_layer_get_layer(s_time_layer));
}
static void main_window_unload(Window *window) {
// Destroy TextLayer
text_layer_destroy(s_time_layer);
}
static void init() {
// Create main Window element and assign to pointer
s_main_window = window_create();
// Set handlers to manage the elements inside the Window
window_set_window_handlers(s_main_window, (WindowHandlers) {
.load = main_window_load,
.unload = main_window_unload
});
// Show the Window on the watch, with animated=true
window_stack_push(s_main_window, true);
// Make sure the time is displayed from the start
update_time();
// Register with TickTimerService
tick_timer_service_subscribe(MINUTE_UNIT, tick_handler);
}
static void deinit() {
// Destroy Window
window_destroy(s_main_window);
}
int main(void) {
init();
app_event_loop();
deinit();
}
I'm using the CloudPebble SDK.
I got it, PBL_IF_ROUND_ELSE works only with 3.X SDK (I was using the 2.X).
"PBL_IF_ROUND_ELSE(58, 52)" Only works with Pebble Time or SDK3.
You can replace "PBL_IF_ROUND_ELSE(58, 52)" with a range between 0 and 100. 0 meaning it will be at the top of the screen. 100 means it will be at the bottom of the screen.
Replace the "PBL_IF_ROUND_ELSE(58, 52)" with a 0. That should do the trick. Im assuming you are trying to run this program on the aplite version?
So I am trying to implement scrolling using this tutorial as a starting point.
I am running the tests on a Desktop.
I added an ActionGestureListener to the stage so I could call the pan(...) function. It works, but when I try to scroll, it looks really laggy, sort of like it's "vibrating".
What am I missing?
Here is what I have so far:
public class Store extends ScreenAdapter {
SpriteBatch spritebatch;
Stage stage;
Texture texture;
Image image;
Group background, foreground;
#Override
public void show() {
spritebatch = new SpriteBatch();
stage = new Stage();
background = new Group();
foreground = new Group();
texture = new Texture("badlogic.jpg");
image = new Image(texture);
//Building background/foreground.
background.addActor(image);
//Adding to stage.
stage.addActor(background);
stage.addActor(foreground);
stage.addListener(new ActorGestureListener() {
// TODO Auto-generated method stub
#Override
public void pan(InputEvent event, float x, float y, float deltaX, float deltaY) {
stage.getCamera().translate(-deltaX, -deltaY, 0);
stage.getCamera().update();
//System.out.println(x + ", " + y + ", " + " " + deltaX + ", " + deltaY);
}
});
Gdx.input.setInputProcessor(stage);
}
#Override
public void render(float delta){
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
spritebatch.setProjectionMatrix(stage.getCamera().combined);
spritebatch.begin();
stage.draw();
spritebatch.end();
}
#Override
public void resize(int width, int height){
System.out.println("resize() executed.");
//stage.getViewport().update(width, height, true);
}
#Override
public void dispose(){
stage.dispose();
texture.dispose();
spritebatch.dispose();
}
}
You should not re-allocate memory for your field objects in your show method. That will drive the garbage collector crazy and probably cause some lag like you're seeing. Move all the new statements from show() into the class constructor or directly onto the field members like this:
public class Store extends ScreenAdapter {
SpriteBatch spritebatch = new SpriteBatch();
Stage stage = new Stage();
// ETC...
That way, the memory for those objects will only be allocated once at object creation.
**EDIT: I just looked and saw that the show method should not be getting repeatedly called like I assumed it was so the above might not work.
I finally got rid of the "vibrating" by editing the translate call.
stage.getCamera().translate(-deltaX / 2, -deltaY / 2, 0);
Instead of dividing by 2, it could be 3 or whatever increment you want. I feel this is solution is more like putting a band-aid on a problem, rather than actually fixing what's wrong. But it has the appearance of something that works, so I will go with it.
I am using a loop to invoke double buffering painting. This, together with overriding my only Panel's repaint method, is designed to pass complete control of repaint to my loop and only render when it necessary (i.e. some change was made in the GUI).
This is my rendering routine:
Log.write("renderer painting");
setNeedsRendering(false);
Graphics g = frame.getBufferStrategy().getDrawGraphics();
g.setFont(font);
g.setColor(Color.BLACK);
g.fillRect(0, 0, window.getWidth(),window.getHeight());
if(frame != null)
window.paint(g);
g.dispose();
frame.getBufferStrategy().show();
As you can see, it is pretty standard. I get the grpahics object from the buffer strategy (initialized to 2), make it all black and pass it to the paint method of my "window" object.
After window is done using the graphics object, I dispose of it and invoke show on the buffer strategy to display the contents of the virtual buffer.
It is important to note that window passes the graphics object to many other children components the populate the window and each one, in turn, uses the same instance of the graphics object to draw something onto the screen: text, shapes, or images.
My problem begins to show when the system is running and a large image is rendered. The image appears to be cut into seveeal pieces and drawn again and again (3-4 times) with different offsets inside of where the image is supposed to be rendered. See my attached images:
This is the original image:
alt text http://img109.imageshack.us/img109/8308/controller.png
This is what I get:
alt text http://img258.imageshack.us/img258/3248/probv.png
Note that in the second picture, I am rendering shapes over the picture - these are always at the correct position.
Any idea why this is happening?
If I save the image to file, as it is in memory, right before the call to g.drawImage(...) it is identical to the original.
Uh, you are using Swing ?
Normally Swing automatically renders the image, you can't switch it off. The repaint()
method is out of bounds because Swing has a very complicated rendering routine due to
method compatibility for AWT widgets and several optimizations, inclusive drawing only
when necessary !
If you want to use the High-Speed Drawing API, you use a component with a BufferStrategy
like JFrame and Window, use
setIgnoreRepaint(false);
to switch off Swing rendering, set up a drawing loop and paint the content itself.
Or you can use JOGL for OpenGL rendering. The method you are using seems completely
at odds with correct Java2D usage.
Here the correct use:
public final class FastDraw extends JFrame {
private static final transient double NANO = 1.0e-9;
private BufferStrategy bs;
private BufferedImage frontImg;
private BufferedImage backImg;
private int PIC_WIDTH,
PIC_HEIGHT;
private Timer timer;
public FastDraw() {
timer = new Timer(true);
JMenu menu = new JMenu("Dummy");
menu.add(new JMenuItem("Display me !"));
menu.add(new JMenuItem("Display me, too !"));
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
setJMenuBar(menuBar);
setIgnoreRepaint(true);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
super.windowClosing(evt);
timer.cancel();
dispose();
System.exit(0);
}
});
try {
backImg = javax.imageio.ImageIO.read(new File("MyView"));
frontImg = javax.imageio.ImageIO.read(new File("MyView"));
}
catch (IOException e) {
System.out.println(e.getMessage());
}
PIC_WIDTH = backImg.getWidth();
PIC_HEIGHT = backImg.getHeight();
setSize(PIC_WIDTH, PIC_HEIGHT);
createBufferStrategy(1); // Double buffering
bs = getBufferStrategy();
timer.schedule(new Drawer(),0,20);
}
public static void main(String[] args) {
new FastDraw();
}
private class Drawer extends TimerTask {
private VolatileImage img;
private int count = 0;
private double time = 0;
public void run() {
long begin = System.nanoTime();
Graphics2D g = (Graphics2D) bs.getDrawGraphics();
GraphicsConfiguration gc = g.getDeviceConfiguration();
if (img == null)
img = gc.createCompatibleVolatileImage(PIC_WIDTH, PIC_HEIGHT);
Graphics2D g2 = img.createGraphics();
// Zeichenschleife
do {
int valStatus = img.validate(gc);
if (valStatus == VolatileImage.IMAGE_OK)
g2.drawImage(backImg,0,0,null);
else {
g.drawImage(frontImg, 0, 0, null);
}
// volatile image is ready
g.drawImage(img,0,50,null);
bs.show();
} while (img.contentsLost());
time = NANO*(System.nanoTime()-begin);
count++;
if (count % 100 == 0)
System.out.println(1.0/time);
}
}