Trying to create native module for my react-native android application. Codes below is my native java to render / display map using mapsforge library.
I need help please, I need to have a function that returns the instance of the application and if possible it is inside the class that extends LinearLayout. I need to call the function as parameter for the AndroidGraphicFactory.createInstance(InstanceOfTheApplication). You think what I am doing is possible?
import android.content.Context;
import android.location.LocationManager;
import android.os.Environment;
import android.os.StrictMode;
import android.widget.LinearLayout;
import org.mapsforge.core.model.LatLong;
import org.mapsforge.map.android.graphics.AndroidGraphicFactory;
import org.mapsforge.map.android.layers.MyLocationOverlay;
import org.mapsforge.map.android.util.AndroidUtil;
import org.mapsforge.map.android.view.MapView;
import org.mapsforge.map.datastore.MapDataStore;
import org.mapsforge.map.layer.cache.TileCache;
import org.mapsforge.map.layer.renderer.TileRendererLayer;
import org.mapsforge.map.model.MapViewPosition;
import org.mapsforge.map.reader.MapFile;
import org.mapsforge.map.rendertheme.InternalRenderTheme;
import java.io.File;
public class CustomMapView extends LinearLayout {
private Context context;
private MapView mapView;
private TileCache tileCache;
private TileRendererLayer tileRendererLayer;
private MyLocationOverlay myLocationOverlay;
private MapViewPosition mapViewPosition;
private LocationManager locationManager;
private static final String map = "philippines.map";
public CustomMapView(Context context) {
super(context);
// set context
this.context = context;
// need help here ...
AndroidGraphicFactory.createInstance(this.getApplication());
// inflate map.xml | setContentView
inflate(this.context, R.layout.map, this);
// create map layout
create();
// start map
start();
}
/**
* Create map layout
* and controls.
*/
private void create() {
this.mapView = (MapView) findViewById(R.id.mapView);
this.mapView.setClickable(true);
this.mapView.getMapScaleBar().setVisible(true);
this.mapView.setBuiltInZoomControls(true);
this.mapView.getMapZoomControls().setZoomLevelMin((byte) 10);
this.mapView.getMapZoomControls().setZoomLevelMax((byte) 20);
// create a tile cache of suitable size
this.tileCache = AndroidUtil.createTileCache(
context,
"mapcache",
mapView.getModel().displayModel.getTileSize(),
1f,
this.mapView.getModel().frameBufferModel.getOverdrawFactor()
);
}
/**
* Start map
*/
private void start() {
this.mapView.getModel().mapViewPosition.setCenter(new LatLong(14.788405, 121.069563));
this.mapView.getModel().mapViewPosition.setZoomLevel((byte) 12);
// tile renderer layer using internal render theme
MapDataStore mapDataStore = new MapFile(getMapFile());
this.tileRendererLayer = new TileRendererLayer(
tileCache,
mapDataStore,
this.mapView.getModel().mapViewPosition,
false,
true,
true,
AndroidGraphicFactory.INSTANCE
);
tileRendererLayer.setXmlRenderTheme(InternalRenderTheme.OSMARENDER);
// only once a layer is associated with a mapView the rendering starts
this.mapView.getLayerManager().getLayers().add(tileRendererLayer);
}
/**
* Get map file
*
* #return
*/
private File getMapFile() {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// absolute path of internal Downloads folder
String dirDownloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
File file = new File(dirDownloads + "/" + map);
return file;
}
}
Related
When following Cubicoder's modding tutorial for Forge 1.12.2, and creating my first item, the texture for the item will not load. I have double checked all of my code against his code. I have my latest log here. I have my registration handler RegistrationHandler.java down below.
package notacyborg.tutorialmod;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraftforge.event.RegistryEvent.Register;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import notacyborg.tutorialmod.util.RegistryUtil;
#EventBusSubscriber(modid = TutorialMod.MODID)
public class RegistrationHandler
{
#SubscribeEvent
public static void registerItems(Register<Item> event)
{
final Item[] items = {
RegistryUtil.setItemName(new Item(), "first_item").setCreativeTab(CreativeTabs.MISC)
};
event.getRegistry().registerAll(items);
}
}
ModelRegistrationHandler.java
package notacyborg.tutorialmod.client;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import notacyborg.tutorialmod.TutorialMod;
import notacyborg.tutorialmod.init.ModItems;
#EventBusSubscriber(value = Side.CLIENT, modid = TutorialMod.MODID)
public class ModelRegistrationHandler
{
#SubscribeEvent
public static void registerModels(ModelRegistryEvent event)
{
registerModel(ModItems.FIRST_ITEM, 0);
}
private static void registerModel(Item item, int meta)
{
ModelLoader.setCustomModelResourceLocation(item, meta,
new ModelResourceLocation(item.getRegistryName(), "inventory"));
}
}
And my first_item.json model file.
{
"parent": "item/generated",
"textures": {
"layer0": "tutorialmod:textures/items/first_item"
}
}
Any help is appreciated!
Your error log says that it was not able to find the model file of your first_item. Make sure that you have put your first_item.json (model file) in assets/Your-Mod-ID/models/item/first_item.json
In your first_item.json file, line 4 should be:
"textures": {
"layer0": "tutorialmod:item/first_item"
}
Try it out and post an error log too if you encounter any further errors.
Please forgive me if this has been asked but I have not found any matches yet.
I have some PDF files where images are duplicated on each page's resources but never used in its content stream. I think this is causing the PDFSplit command to create very bloated pages. Is there any utility code or examples to clean up unused resources like this? Maybe a starting point for me to get going?
I was able to clean up the resources for each page by gathering a list of the images used inside the page's content stream. With the list of images, I then check the resources for the page and remove any that weren't used. See the PageExtractor.stripUnusedImages below for implementation details.
The resource object was shared between pages so I also had to make sure each page had its own copy of the resource object before removing images. See PageExtractor.copyResources below for implementation details.
The page splitter:
package org.apache.pdfbox.examples;
import org.apache.pdfbox.contentstream.operator.Operator;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.interactive.action.PDAction;
import org.apache.pdfbox.pdmodel.interactive.action.PDActionGoTo;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDDestination;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageDestination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class PageExtractor {
private final Logger log = LoggerFactory.getLogger(this.getClass());
public PDDocument extractPage(PDDocument source, Integer pageNumber) throws IOException {
PDDocument targetPdf = new PDDocument();
targetPdf.getDocument().setVersion(source.getVersion());
targetPdf.setDocumentInformation(source.getDocumentInformation());
targetPdf.getDocumentCatalog().setViewerPreferences(source.getDocumentCatalog().getViewerPreferences());
PDPage sourcePage = source.getPage(pageNumber);
PDPage targetPage = targetPdf.importPage(sourcePage);
targetPage.setResources(sourcePage.getResources());
stripUnusedImages(targetPage);
stripPageLinks(targetPage);
return targetPdf;
}
/**
* Collect the images used from a custom PDFStreamEngine (BI and DO operators)
* Create an empty COSDictionary
* Loop through the page's XObjects that are images and add them to the new COSDictionary if they were found in the PDFStreamEngine
* Assign the newly filled COSDictionary to the page's resource as COSName.XOBJECT
*/
protected void stripUnusedImages(PDPage page) throws IOException {
PDResources resources = copyResources(page);
COSDictionary pageObjects = (COSDictionary) resources.getCOSObject().getDictionaryObject(COSName.XOBJECT);
COSDictionary newObjects = new COSDictionary();
Set<String> imageNames = findImageNames(page);
Iterable<COSName> xObjectNames = resources.getXObjectNames();
for (COSName xObjectName : xObjectNames) {
if (resources.isImageXObject(xObjectName)) {
Boolean used = imageNames.contains(xObjectName.getName());
if (used) {
newObjects.setItem(xObjectName, pageObjects.getItem(xObjectName));
} else {
log.info("Found unused image: name={}", xObjectName.getName());
}
} else {
newObjects.setItem(xObjectName, pageObjects.getItem(xObjectName));
}
}
resources.getCOSObject().setItem(COSName.XOBJECT, newObjects);
page.setResources(resources);
}
/**
* It is necessary to copy the page's resources since it can be shared with other pages. We must ensure changes
* to the resources are scoped to the current page.
*/
protected PDResources copyResources(PDPage page) {
return new PDResources(new COSDictionary(page.getResources().getCOSObject()));
}
protected Set<String> findImageNames(PDPage page) throws IOException {
Set<String> imageNames = new HashSet<>();
PdfImageStreamEngine engine = new PdfImageStreamEngine() {
#Override
void handleImage(Operator operator, List<COSBase> operands) {
COSName name = (COSName) operands.get(0);
imageNames.add(name.getName());
}
};
engine.processPage(page);
return imageNames;
}
/**
* Borrowed from PDFBox page splitter
*
* #see org.apache.pdfbox.multipdf.Splitter#processAnnotations(org.apache.pdfbox.pdmodel.PDPage)
*/
protected void stripPageLinks(PDPage imported) throws IOException {
List<PDAnnotation> annotations = imported.getAnnotations();
for (PDAnnotation annotation : annotations) {
if (annotation instanceof PDAnnotationLink) {
PDAnnotationLink link = (PDAnnotationLink) annotation;
PDDestination destination = link.getDestination();
if (destination == null && link.getAction() != null) {
PDAction action = link.getAction();
if (action instanceof PDActionGoTo) {
destination = ((PDActionGoTo) action).getDestination();
}
}
if (destination instanceof PDPageDestination) {
// TODO preserve links to pages within the splitted result
((PDPageDestination) destination).setPage(null);
}
}
// TODO preserve links to pages within the splitted result
annotation.setPage(null);
}
}
}
The stream reader used to analyze the page's images:
package org.apache.pdfbox.examples;
import org.apache.pdfbox.contentstream.PDFStreamEngine;
import org.apache.pdfbox.contentstream.operator.Operator;
import org.apache.pdfbox.contentstream.operator.OperatorProcessor;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.graphics.PDXObject;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
import org.apache.pdfbox.pdmodel.graphics.form.PDTransparencyGroup;
import java.io.IOException;
import java.util.List;
abstract public class PdfImageStreamEngine extends PDFStreamEngine {
PdfImageStreamEngine() {
addOperator(new DrawObjectCounter());
}
abstract void handleImage(Operator operator, List<COSBase> operands);
protected class DrawObjectCounter extends OperatorProcessor {
#Override
public void process(Operator operator, List<COSBase> operands) throws IOException {
if (operands != null && isImage(operands.get(0))) {
handleImage(operator, operands);
}
}
protected Boolean isImage(COSBase base) throws IOException {
if (!(base instanceof COSName)) {
return false;
}
COSName name = (COSName)base;
if (context.getResources().isImageXObject(name)) {
return true;
}
PDXObject xObject = context.getResources().getXObject(name);
if (xObject instanceof PDTransparencyGroup) {
context.showTransparencyGroup((PDTransparencyGroup)xObject);
} else if (xObject instanceof PDFormXObject) {
context.showForm((PDFormXObject)xObject);
}
return false;
}
#Override
public String getName() {
return "Do";
}
}
}
I would like to ask about library APACHE POI. I have a .pptx file and with the example which I found on internet I split each slide into separate images. This works great when slide containts .png, .jpeg images but as soon as I have .emf files in slide this image disappear. So I want to have the same copy of slide but with .emf file as well. Is this possible?
version: Apache POI 3.12
Thanks a lot
As mentioned in the comments, EMF is not supported out of the box ... and as FreeHep decided to have a LGPL license it's unlikely that we will include in our release.
In POI you basically have two options to provide a custom image renderer:
implement and register your ImageRenderer implementation in the Graphics2D context via setRenderingHint(Drawable.IMAGE_RENDERER, new MyImageRendener()). The drawback is, that it will be called for any images and you loose the default handling for bitmap/wmf images
or provide a custom DrawFactory which serves your own DrawPictureShape implementation - as in the example below - which only diverts to the EMF renderer when necessary
(looking at this example, the current POI ImageRenderer handling doesn't look flexible and instead of having a global handler, it might be better to register a handler per content-type ...)
Apart of the usual POI component I've included freehep-graphics2d, freehep-graphicsbase, freehep-graphicsio, freehep-graphicsio-emf and freehep-io.
The example is far from being finished, but I guess you get at least a kick-start:
package org.apache.poi.xslf;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import org.apache.poi.sl.draw.DrawFactory;
import org.apache.poi.sl.draw.DrawPictureShape;
import org.apache.poi.sl.draw.Drawable;
import org.apache.poi.sl.draw.ImageRenderer;
import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.sl.usermodel.PictureData.PictureType;
import org.apache.poi.sl.usermodel.PictureShape;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFPictureShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.freehep.graphicsio.emf.EMFInputStream;
import org.freehep.graphicsio.emf.EMFRenderer;
import org.junit.Test;
public class TestEMFRender {
private final static POILogger LOG = POILogFactory.getLogger(TestEMFRender.class);
#Test
public void render() throws Exception {
XMLSlideShow ppt = getDummy();
Dimension pgsize = ppt.getPageSize();
BufferedImage img = new BufferedImage((int)pgsize.getWidth(), (int)pgsize.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = initGraphicsCtx(img);
// draw stuff
ppt.getSlides().get(0).draw(graphics);
// save the result
File outfile = new File("bla.png");
ImageIO.write(img, "PNG", outfile);
// cleanup
graphics.dispose();
img.flush();
ppt.close();
}
static XMLSlideShow getDummy() throws IOException {
XMLSlideShow ppt = new XMLSlideShow();
FileInputStream fis = new FileInputStream("kiwilogo.emf");
PictureData pd = ppt.addPicture(fis, PictureType.EMF);
fis.close();
XSLFSlide sl = ppt.createSlide();
XSLFPictureShape ps = sl.createPicture(pd);
ps.setAnchor(new Rectangle2D.Double(100, 100, 100, 100));
return ppt;
}
static Graphics2D initGraphicsCtx(BufferedImage img) {
Graphics2D graphics = img.createGraphics();
// default rendering options
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
// custom draw factory
DrawFactory df = new DrawFactory(){
public DrawPictureShape getDrawable(PictureShape<?,?> shape) {
return new DrawPictureShapeEmf(shape);
}
};
graphics.setRenderingHint(Drawable.DRAW_FACTORY, df);
df.fixFonts(graphics);
return graphics;
}
static class DrawPictureShapeEmf extends DrawPictureShape {
public DrawPictureShapeEmf(PictureShape<?,?> shape) {
super(shape);
}
#Override
public void drawContent(Graphics2D graphics) {
PictureData data = getShape().getPictureData();
if(data == null) return;
Rectangle2D anchor = getAnchor(graphics, getShape());
Insets insets = getShape().getClipping();
try {
String contentType = data.getContentType();
ImageRenderer renderer =
PictureType.EMF.contentType.equals(contentType)
? new ImgRenderer()
: super.getImageRenderer(graphics, contentType);
renderer.loadImage(data.getData(), data.getContentType());
renderer.drawImage(graphics, anchor, insets);
} catch (IOException e) {
LOG.log(POILogger.ERROR, "image can't be loaded/rendered.", e);
}
}
}
static class ImgRenderer implements ImageRenderer {
EMFRenderer emfRenderer;
public void loadImage(InputStream data, String contentType) throws IOException {
emfRenderer = new EMFRenderer(new EMFInputStream(data));
}
public void loadImage(byte[] data, String contentType) throws IOException {
loadImage(new ByteArrayInputStream(data), contentType);
}
public Dimension getDimension() {
return emfRenderer.getSize();
}
public void setAlpha(double alpha) {
}
public BufferedImage getImage() {
return null;
}
public BufferedImage getImage(Dimension dim) {
return null;
}
public boolean drawImage(Graphics2D ctx, Rectangle2D graphicsBounds) {
return drawImage(ctx, graphicsBounds, null);
}
public boolean drawImage(Graphics2D ctx, Rectangle2D graphicsBounds, Insets clip) {
AffineTransform at = ctx.getTransform();
try {
Dimension emfDim = emfRenderer.getSize();
// scale output bounds to image bounds
ctx.translate(graphicsBounds.getX(), graphicsBounds.getY());
ctx.scale(graphicsBounds.getWidth()/emfDim.getWidth(), graphicsBounds.getHeight()/emfDim.getHeight());
// TODO: handle clipping
emfRenderer.paint(ctx);
return true;
} catch (RuntimeException e) {
// TODO: logging
return false;
} finally {
ctx.setTransform(at);
}
}
}
}
I have a class called "HudBarView" which takes care of the drawing of the HUD Bar at the top of the screen(Pause button, score, etc).
This class extends the Group class(scene2d).
Another class I have is "HUDManager" which takes care of all the HUD work in the game, including HUD Bar.
Now, currently I have only a pause button in my HUD Bar but the problem is - it is visible only after I resize the screen. Very weird problem.
Here is my HudBarView class:
package views.hud.views;
import views.renderers.HUDManager;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import engine.helpers.AssetsManager;
import engine.helpers.Values;
public class HUDBarView extends Group{
private ImageButton pause;
private HUDManager hud_manager;
private Skin skin;
public HUDBarView(HUDManager hud_manager) {
this.hud_manager = hud_manager;
initiate();
}
private void initiate() {
skin = new Skin(AssetsManager.getAsset(Values.BUTTONS_PACK, TextureAtlas.class));
pause = new ImageButton(skin.getDrawable("pause"));
pause.setSize(Values.Pause_Width, Values.Pause_Height);
pause.setPosition(Values.SCREEN_WIDTH - pause.getWidth(), Values.SCREEN_HEIGHT- pause.getHeight());
addActor(pause);
}
}
Here is my HUDManager class:
package views.renderers;
import views.hud.ParticleEffectsActor;
import views.hud.views.HUDBarView;
import aurelienribon.tweenengine.TweenManager;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import engine.helpers.AssetsManager;
import engine.helpers.UIHelper;
import engine.helpers.Values;
public class HUDManager extends Group {
private Stage stage;
private Skin skin;
private Image text;
private HUDBarView hudView;
public HUDManager(Stage stage) {
this.stage = stage;
initiate();
addActor(hudView);
addActor(particles);
}
public void initiate() {
skin = AssetsManager.getAsset(Values.GAME_SKIN_PACK, Skin.class);
hudView = new HUDBarView(this);
particles = new ParticleEffectsActor();
}
public Stage getStage() {
return stage;
}
}
Here are some photos that will help you understand the problem a little bit better:
Before the screen is resized(it doesn't matter how much the screen is resized):
http://i.gyazo.com/5cc675bde2fcbba7492bba69d4a419c6.png
After the screen is resized:
http://i.gyazo.com/d6814f3e15b903d59dab74b83e95292c.png
P.S Here is my render method inside the Game Screen class(I omitted all the irrelevant parts):
public void render(float delta) {
switch(state) {
case RUN:
// if The asset manager is done loading
if(AssetsManager.update() && !doneLoading) {
doneLoading = true;
hudManager = new HUDManager(stage);
stage.addActor(hudManager);
renderer = new GameRenderer(world, camera, batch);
loadingRenderer.dispose();
} else if(doneLoading) {
renderer.render(delta);
stage.draw();
stage.act(delta);
world.update(delta);
manager.update(delta);
}
// Display loading information
else
loadingRenderer.render(AssetsManager.getProgress()*100);
case PAUSE:
break;
}
}
EDIT: After playing a little bit with the code I found out that if I pause and then resume the game it causes the ImageButton to appear on the screen.
I want to transfer the variables score from GameScreen.as to GameOverScreen.as.
The method from GameOverScreen.as is called getScore(score:Number), that doesn't update the finalScore from the constructor of GameOverScreen.as.
Is there the way to ensure that the finalScore has the same value as the scorePoints from the GameScreen.as? (P.S I tried finding the answer but there's no avail.)
Here's the code:
GameScreen.as
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.net.SharedObject;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.text.*;
/**
* ...
* #author xxxx
*/
public class GameScreen extends MovieClip
{
private var mainClass:main;
private var enemy:Enemy;
private var timer:Timer;
public var scorePoints:Number;
public var gameOverScreen:GameOverScreen;
private var debugValue:Number;
public function GameScreen(passedClass:main)
{
mainClass = passedClass;
gameOverScreen = new GameOverScreen();
enemy = new Enemy();
addChild(enemy);
debugValue = 1;
scorePoints = 0;
addEventListener(Event.ADDED_TO_STAGE, onAdd);
ClickToWinButton.addEventListener(MouseEvent.CLICK, clickToWin);
}
private function clickToWin(e:MouseEvent):void
{
scorePoints += 50;
}
private function onAdd(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, onAdd);
init();
}
private function init():void
{
addEventListener(Event.ENTER_FRAME, gameScreenProgress);
}
public function gameScreenProgress(e:Event):void
{
ScoreText.text = "Score: " + scorePoints;
if (enemy.hitTestPoint(mouseX, mouseY, true))
{
mainClass.showGameOver();
gameOverScreen.getScore(scorePoints);
enemy.removeEnemy();
}
}
}
}
GameOverScreen.as
package
{
import flash.events.Event;
import flash.display.MovieClip;
import flash.net.SharedObject;
import flash.text.*;
/**
* ...
* #author xxxx
*/
public class GameOverScreen extends MovieClip
{
private var mainClass:main;
private var gameScreen:GameScreen;
public var finalScore:Number;
public function GameOverScreen()
{
ScoreText.text = "" + finalScore;
}
public function getScore(score:Number)
{
finalScore = score;
trace(finalScore);
}
}
}
The problem seems to be that your GameOverScreen only updates the ScoreText.text in the constructor. The constructor is only executed when the GameOverScreen is created.
Later, after the GameOverScreen has been created, you call the getScore() method and pass in the final score. But all the getScore() method does is update the finalScore variable... it does not actually update the text field with the actual score.
What you should probably do is remove this line from the constructor:
ScoreText.text = "" + finalScore;
And put it in your getScore() method. I would also consider renaming getScore() to setScore() -- because it is setting the score, not retrieving it...
public function setScore(score:Number)
{
finalScore = score;
trace(finalScore);
ScoreText.text = "" + finalScore;
}