getSelectedIndex JComboBox - jcheckbox

I have a school assignment to change a GUI Calculator from RadioButton to JComboBox. I have made the change but I have some issue.
The first is for some reason when I choose to calculate, it does not work
and I need it to be calculated directly after choosing option from the JComboBox.
I must use selected Index method as a part of the assignment.
Here is my code:
<code>
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.TitledBorder;
public class TaschenrechnerGUIV2 extends JFrame{
private static final long serialVersionUID = 3006212012028893840L;
private JTextField eingabe1, eingabe2;
double x, y, ergebnis = 0;
String [] option = {"addition", "subtraktion", "multiplikation", "division"};//array JList
private JComboBox <String> optionComboBox = new JComboBox <String>(option);//need to import the JComboBox
private JButton schaltflaecheBerechnen, schaltflaecheBeenden;
private JLabel ausgabe;
class MeinListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("ende"))
System.exit(0);
if (e.getActionCommand().equals("rechnen"))
ausgabe.setText(berechnen());
if (e.getSource() instanceof JComboBox){
ausgabe.setText(berechnen());
}
}
}
public TaschenrechnerGUIV2(String titel) {
super(titel);
JPanel panelEinAus, panelBerechnung, panelButtons, gross;
panelEinAus = panelEinAusErzeugen();
panelBerechnung = panelBerechnungErzeugen();
panelButtons = panelButtonErzeugen();
gross = new JPanel();
gross.add(panelEinAus);
gross.add(panelBerechnung);
add(gross,BorderLayout.CENTER);
add(panelButtons, BorderLayout.EAST);
optionComboBox.setEnabled(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
}
private JPanel panelEinAusErzeugen() {
JPanel tempPanel = new JPanel();
eingabe1 = new JTextField(10);
eingabe2 = new JTextField(10);
ausgabe = new JLabel("");
tempPanel.setLayout(new GridLayout(0,2,10,10));
tempPanel.add(new JLabel("Zahl 1:"));
tempPanel.add(eingabe1);
tempPanel.add(new JLabel("Zahl 2: "));
tempPanel.add(eingabe2);
tempPanel.add(new JLabel("Ergebnis: "));
tempPanel.add(ausgabe);
tempPanel.setBorder(new TitledBorder("Ein- und Ausgabe"));
return tempPanel;
}
private JPanel panelBerechnungErzeugen() {
JPanel tempPanel = new JPanel();
tempPanel.add(optionComboBox);//add the JComboBox to the panel
tempPanel.setLayout(new GridLayout(0,1));
tempPanel.setBorder(new TitledBorder("Operation: "));
return tempPanel;
}
private JPanel panelButtonErzeugen() {
JPanel tempPanel = new JPanel();
schaltflaecheBeenden = new JButton(" Beenden ");
schaltflaecheBeenden.setActionCommand("ende");
schaltflaecheBerechnen = new JButton("Berechnen");
schaltflaecheBerechnen.setActionCommand("rechnen");
tempPanel.setLayout(new GridLayout(0,1));
tempPanel.add(schaltflaecheBerechnen);
tempPanel.add(new JLabel());
tempPanel.add(schaltflaecheBeenden);
MeinListener listener = new MeinListener();
schaltflaecheBeenden.addActionListener(listener);
schaltflaecheBerechnen.addActionListener(listener);
optionComboBox.addActionListener(listener);//adding a listener to the JComboBox
return tempPanel;
}
private String berechnen() {
double x, y, ergebnis = 0;
boolean fehlerFlag = false;
try {
x = Double.parseDouble(eingabe1.getText());
}
catch (Exception NumberFormatException) {
fehlermeldung(eingabe1);
return ("Nicht definiert");
}
try {
y = Double.parseDouble(eingabe2.getText());
}
catch (Exception NumberFormatException) {
fehlermeldung(eingabe2);
return ("Nicht definiert");
}
if (optionComboBox.getSelectedIndex() ==0){
ergebnis = x + y;
}
if (optionComboBox.getSelectedIndex() ==1){
ergebnis = x - y;
}
if (optionComboBox.getSelectedIndex() ==2){
ergebnis = x * y;
}
if (optionComboBox.getSelectedIndex() ==3){
if(y !=0)
ergebnis = x / y;
}
else
fehlerFlag = true;
if (fehlerFlag == false) {
DecimalFormat formatFolge = new DecimalFormat("0.##");
return (formatFolge.format(ergebnis));
}
else return ("Nicht definiert"); }
private void fehlermeldung(JTextField eingabefeld) {
JOptionPane.showMessageDialog(this, "Ihre Eingabe ist nicht gültig","Eingabefehler", JOptionPane.ERROR_MESSAGE);
eingabefeld.requestFocus();
}
public static void main (String [] arg){
new TaschenrechnerGUIV2("Taschenrechner V2"); }}
</code>

You forgot to include what the ActionListener should listen to.
zB.
object set = e.getSorce();
if(set instanceof JComboBox){
if (optionComboBox.getSelectedIndex() ==0){
ergebnis = x + y;
}
if (optionComboBox.getSelectedIndex() ==1){
ergebnis = x - y;
}
if (optionComboBox.getSelectedIndex() ==2){
ergebnis = x * y;
}
if (optionComboBox.getSelectedIndex() ==3){
if(y !=0)
ergebnis = x / y;
}
}

Related

Rubberband effect for scrolling containers

I'd like to have a rubberband effect on scrolling containers for which I feel the "tensile scrolling" that is build into the Component base class is no sufficient replacement.
Is there a reasonably feasible way like disabling the default overscroll behavior in order to control the property scrollY in a way like in this example - How to create the rubberband effect?
Since there was no answer to my question I answer it myself. Beware that I am not an expert and therefore this might not fit Your purpose!
The default overscroll behaviour can be overridden by extending the Container class and overriding the pointer methods without calling their super methods.
Here is an example:
import com.codename1.ui.Component;
import com.codename1.ui.Container;
import com.codename1.ui.Form;
import com.codename1.ui.Graphics;
import com.codename1.ui.Label;
import com.codename1.ui.animations.Motion;
import com.codename1.ui.geom.Point;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.ui.layouts.BoxLayout;
public class FormOverscroll extends Form {
FormOverscroll() {
super("FormOverscroll");
setScrollable(false);
setLayout(new BorderLayout());
Container container = new Container(BoxLayout.y()) {
boolean bounce = false;
Motion motion = null;
Point pointPressed = null;
long millisPoint = 0;
int scrollYPressed = 0, scrollYPrevious = 0;
{
// setTensileDragEnabled(false);
setScrollableY(true);
}
#Override
protected boolean isStickyDrag() {
return true;
}
#Override
public void pointerPressed(int x, int y) {
pointPressed = new Point(x, y);
scrollYPressed = scrollYPrevious = getScrollY();
millisPoint = System.currentTimeMillis();
motion = null;
bounce = false;
}
#Override
public void pointerDragged(int x, int y) {
if (null == pointPressed) {
return;
}
int yDist = y - pointPressed.getY();
int scrollY = scrollYPressed - yDist;
if (scrollY < 0) {
Motion motionRubberband = Motion.createCubicBezierMotion(0, scrollY, getHeight(), 0f, 1.2f, 0.5f, 0.6f);
motionRubberband.setStartTime(0);
motionRubberband.setCurrentMotionTime(Math.abs(scrollY));
scrollY = motionRubberband.getValue();
}
setScrollY(scrollY);
}
float getVelocity(int scrollY) {
long millisNow = System.currentTimeMillis();
long timediff = millisNow - millisPoint;
float diff = scrollYPrevious - scrollY;
float velocity = (diff / timediff) * -1f;
scrollYPrevious = scrollY;
millisPoint = millisNow;
return velocity;
}
#Override
public void pointerReleased(int x, int y) {
if (null == pointPressed) {
return;
}
int yDist = y - pointPressed.getY();
int scrollY = scrollYPressed - yDist;
float velocity = getVelocity(scrollY);
motion = Motion.createFrictionMotion(scrollY, Integer.MIN_VALUE, velocity, 0.0007f);
motion.start();
getComponentForm().registerAnimated(this);
pointPressed = null;
}
#Override
public boolean animate() {
boolean animate = super.animate();
if (null != motion) {
int scrollY = motion.getValue();
setScrollY(scrollY);
int target = 0;
if (scrollY < target && !bounce) {
createRubberbandMotion(scrollY, target);
bounce = true;
motion.start();
}
int maxScrollY = Math.max(target, getScrollDimension().getHeight() - getHeight());
if (scrollY > maxScrollY && !bounce) {
createRubberbandMotion(scrollY, maxScrollY);
bounce = true;
motion.start();
}
scrollYPrevious = scrollY;
if (motion.isFinished()) {
motion = null;
}
return true;
}
return animate;
}
private void createRubberbandMotion(int source, int target) {
motion = Motion.createCubicBezierMotion(source, target, 500, 0.0f, 1.0f, 1.2f, 1.0f);
}
#Override
public Component getComponentAt(int x, int y) {
return this;
}
#Override
public void paint(Graphics aGraphics) {
super.paint(aGraphics);
}
};
for (int index = 0; index < 100; index++) {
container.add(new Label("Zeile " + index));
}
add(BorderLayout.CENTER, container);
}
}

Why does this image rendering benchmark crash on IOS but not in the simulator?

I tried to get a grasp of image rendering performance and created some code which draws full screen images using mutable images and PNGs.
The code runs fine in the simulator but on an iPhone SE it crashes after 50 seconds or short before a million images.
Is it a bug or is there another explanation since it doesn't crash in the simulator and I cannot see a memory leak in jvisualvm?
Here is the code:
public class FormMeasureImage extends Form implements Painter {
abstract class Wallpaper implements Painter {
private Component componentParent;
public Wallpaper(Component aComponentParent) {
componentParent = aComponentParent;
}
public void paint(Graphics aGraphics, Rectangle aRectangle) {
aGraphics.drawImage(
getImage(new Dimension(componentParent.getWidth(), componentParent.getHeight())),
0,
0);
}
public abstract Image getImage(Dimension aDimension);
}
class WallpaperTiledIcons extends Wallpaper {
private Image image;
private Dimension dimension;
public WallpaperTiledIcons(Component aComponentParent) {
super(aComponentParent);
}
public Image getImage(Dimension aDimension) {
if ((null == image || !dimension.equals(aDimension)) && null != aDimension) {
dimension = new Dimension(aDimension);
Label labelPattern = new Label("1234567890");
Style styleLabelPattern = labelPattern.getAllStyles();
styleLabelPattern.setBorder(Border.createEmpty());
styleLabelPattern.setMargin(0, 0, 0, 0);
// byte[] bytes = new byte[4];
// Arrays.fill(bytes, Style.UNIT_TYPE_PIXELS);
// styleLabelPattern.setPaddingUnit(bytes);
styleLabelPattern.setPadding(0, 0, 0, 1);
Dimension preferredSizeLabelPattern = labelPattern.getPreferredSize();
labelPattern.setSize(preferredSizeLabelPattern);
Image imagePattern = Image.createImage(
preferredSizeLabelPattern.getWidth(),
preferredSizeLabelPattern.getHeight(),
0x00000000);
Graphics graphicsImagePattern = imagePattern.getGraphics();
graphicsImagePattern.setAlpha(255);
labelPattern.paint(graphicsImagePattern);
image = Image.createImage(
aDimension.getWidth(),
aDimension.getHeight(),
0xff606060);
Graphics graphics = image.getGraphics();
if (graphics.isAntiAliasingSupported()) {
graphics.setAntiAliased(true);
}
int canvasWidth = preferredSizeLabelPattern.getWidth(), canvasHeight = preferredSizeLabelPattern.getHeight();
int[] clip = graphics.getClip();
Rectangle rectangleClip = new Rectangle(clip[0], clip[1], clip[2], clip[3]);
int columns = (rectangleClip.getX() + rectangleClip.getWidth()) / canvasWidth + 1;
int rows = (rectangleClip.getY() + rectangleClip.getHeight()) / canvasHeight + 1;
for (int row = 0; row < rows; row++) {
for (int column = 0; column < columns; column++) {
int x = canvasWidth * column;
int y = canvasHeight * row;
Rectangle rectangle = new Rectangle(x, y, canvasWidth, canvasHeight);
if (!rectangleClip.intersects(rectangle)) {
continue;
}
graphics.drawImage(imagePattern, x, y);
}
}
}
return image;
}
}
abstract class Stage {
long millisTotal;
long tally;
TextArea textArea;
public Stage(String aName) {
textArea = new TextArea();
textArea.setEditable(false);
getContentPane().add(textArea);
stages.add(this);
}
abstract void perform();
abstract boolean isPainted();
}
private Wallpaper wallpaper;
private List<Stage> stages = new ArrayList<>();
private Iterator<Stage> iteratorStages;
private Image imageEncoded;
public FormMeasureImage() {
super("FormMeasureImage", new BoxLayout(BoxLayout.Y_AXIS));
setScrollableX(false);
setScrollableY(true);
Style styleForm = getAllStyles();
styleForm.setBgTransparency(255);
styleForm.setBgPainter(this);
TextArea textArea = new TextArea();
textArea.setEditable(false);
textArea.setText("Measuring image throughput.");
add(textArea);
}
#Override
public void paint(Graphics aGraphics, Rectangle aRectangle) {
if (null == iteratorStages) {
new Stage("create") {
void perform() {
long millisBefore = System.currentTimeMillis();
wallpaper = new WallpaperTiledIcons(FormMeasureImage.this);
wallpaper.getImage(aRectangle.getSize());
millisTotal += System.currentTimeMillis() - millisBefore;
tally++;
textArea.setText("create: " + millisTotal + " / " + tally);
}
boolean isPainted() {
return false;
}
};
new Stage("mutable") {
void perform() {
long millisBefore = System.currentTimeMillis();
for (int index = 0; index < 1000; index++) {
wallpaper.paint(aGraphics, aRectangle);
tally++;
}
millisTotal += System.currentTimeMillis() - millisBefore;
textArea.setText("mutable: " + millisTotal + " / " + tally);
}
boolean isPainted() {
return true;
}
};
new Stage("encoding") {
void perform() {
long millisBefore = System.currentTimeMillis();
try {
millisBefore = System.currentTimeMillis();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.getImageIO().save(wallpaper.getImage(null), byteArrayOutputStream, ImageIO.FORMAT_PNG, 1);
byteArrayOutputStream.close();
imageEncoded = Image.createImage(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
tally++;
millisTotal += System.currentTimeMillis() - millisBefore;
textArea.setText("encoding: " + millisTotal + " / " + tally);
} catch (IOException e) {
throw new RuntimeException(e.toString());
}
millisTotal += System.currentTimeMillis() - millisBefore;
tally++;
textArea.setText("encoding: " + millisTotal + " / " + tally);
}
boolean isPainted() {
return false;
}
};
new Stage("encoded") {
void perform() {
long millisBefore = System.currentTimeMillis();
for (int index = 0; index < 1000; index++) {
aGraphics.drawImage(
imageEncoded,
0,
0);
tally++;
}
millisTotal += System.currentTimeMillis() - millisBefore;
textArea.setText("encoded: " + millisTotal + " / " + tally);
}
boolean isPainted() {
return true;
}
};
iteratorStages = stages.iterator();
}
while (!perform().isPainted()) {;}
}
private Stage perform() {
if (!iteratorStages.hasNext()) {
iteratorStages = stages.iterator();
}
Stage stage = iteratorStages.next();
stage.perform();
return stage;
}
}
It seems that the test case included an EDT violation of decoding off the EDT. This can work for some cases but because of the heavy usage it crashes.
Making UI code threadsafe is a difficult task which is doubly so cross platforms.

How to get all video files from phone internal storage(Nexus 5) in android

I want to get all video files from the internal memory of the device.
I have tried the following ways without getting a result
File file[] = Environment.getExternalStorageDirectory().listFiles();
File file= Environment.getDataDirectory();
File file[] = Environment.getRootDirectory().listFiles();
File file = Environment.getExternalStoragePublicDirectory();
I got the solution for this..Please look into below code
import android.os.Environment;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class ExternalStorage {
public static final String SD_CARD = "sdCard";
public static final String EXTERNAL_SD_CARD = "externalSdCard";
/**
* #return True if the external storage is available. False otherwise.
*/
public static boolean isAvailable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
public static String getSdCardPath() {
return Environment.getExternalStorageDirectory().getPath() + "/";
}
/**
* #return True if the external storage is writable. False otherwise.
*/
public static boolean isWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/**
* #return A map of all storage locations available
*/
public static Map<String, File> getAllStorageLocations() {
Map<String, File> map = new HashMap<String, File>(10);
List<String> mMounts = new ArrayList<String>(10);
List<String> mVold = new ArrayList<String>(10);
mMounts.add("/mnt/sdcard");
mVold.add("/mnt/sdcard");
try {
File mountFile = new File("/proc/mounts");
if(mountFile.exists()){
Scanner scanner = new Scanner(mountFile);
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("/dev/block/vold/")) {
String[] lineElements = line.split(" ");
String element = lineElements[1];
// don't add the default mount path
// it's already in the list.
if (!element.equals("/mnt/sdcard"))
mMounts.add(element);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
File voldFile = new File("/system/etc/vold.fstab");
if(voldFile.exists()){
Scanner scanner = new Scanner(voldFile);
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("dev_mount")) {
String[] lineElements = line.split(" ");
String element = lineElements[2];
if (element.contains(":"))
element = element.substring(0, element.indexOf(":"));
if (!element.equals("/mnt/sdcard"))
mVold.add(element);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < mMounts.size(); i++) {
String mount = mMounts.get(i);
if (!mVold.contains(mount))
mMounts.remove(i--);
}
mVold.clear();
List<String> mountHash = new ArrayList<String>(10);
for(String mount : mMounts){
File root = new File(mount);
if (root.exists() && root.isDirectory() && root.canWrite()) {
File[] list = root.listFiles();
String hash = "[";
if(list!=null){
for(File f : list){
hash += f.getName().hashCode()+":"+f.length()+", ";
}
}
hash += "]";
if(!mountHash.contains(hash)){
String key = SD_CARD + "_" + map.size();
if (map.size() == 0) {
key = SD_CARD;
} else if (map.size() == 1) {
key = EXTERNAL_SD_CARD;
}
mountHash.add(hash);
map.put(key, root);
}
}
}
mMounts.clear();
if(map.isEmpty()){
map.put(SD_CARD, Environment.getExternalStorageDirectory());
}
return map;
}
}

Creating Enemy Cone of vision

I am trying to create a cone of vision for my enemy class. Right now it checks to see if the player is within a radius before moving towards them and will move around randomly if they are not. I want to give it vision so the enemy does not always rotate towards the player.
Enemy Class
package
{
import flash.automation.ActionGenerator;
import flash.events.Event;
import flash.geom.Point;
public class Enemy extends GameObject
{
var isDead:Boolean = false;
var speed:Number = 3;
var originalValue:Number = 50;
var changeDirection:Number = originalValue;
var checkDirection:Number = 49;
var numberGen:Number;
//var startTime:int = getTimer();
//var $timer = getTimer();
//var myTimer:int = getTimer();
//var moveTimer:int = timer - $timer;
public function Enemy()
{
super();
target = target_mc;
}
override public function update():void
{
movement();
}
private function movement():void
{
if (changeDirection >= 0)
{
if (changeDirection > checkDirection)
{
numberGen = (Math.random() * 360) / 180 * Math.PI;
}
var velocity:Point = new Point();
var $list:Vector.<GameObject > = getType(Player);
var $currentDistance:Number = Number.MAX_VALUE;
for (var i:int = 0; i < $list.length; i++)
{
var currentPlayer:GameObject = $list[i];
if (MathUtil.isWithinRange(currentPlayer.width,currentPlayer.x,currentPlayer.y,width,x,y))
{
var $delta:Point = new Point ;
$delta.x = currentPlayer.x - x;
$delta.y = currentPlayer.y - y;
if ($currentDistance > $delta.length)
{
$currentDistance = $delta.length;
velocity = $delta;
velocity.normalize(speed);
}
}
}
if(velocity.length == 0)
{
velocity = Point.polar(2, numberGen);
}
changeDirection--;
if (changeDirection == 0)
{
changeDirection = originalValue;
}
}
velocity.x = Math.floor(velocity.x * 10) * .1;
velocity.y = Math.floor(velocity.y * 10) * .1;
moveBy([Wall, Door], velocity.x, velocity.y, collides_mc);
var $collides:GameObject = collision([Player]);
if ($collides != null)
{
destroy();
}
if ($collides == null)
{
$collides = collision([Player],this);
if ($collides != null)
{
$collides.destroy();
}
}
rotation = (Math.atan2(velocity.y, velocity.x) * 180 / Math.PI);
collides_mc.rotation = -rotation;
trace($collides);
}
override public function onCollideX($collision:GameObject):void
{
}
override public function onCollideY($collision:GameObject):void
{
}
}
}
GameObject Class, which contains all the functions and Enemy extends it
package
{
import flash.display.DisplayObject;
import flash.events.Event;
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.sensors.Accelerometer;
import flashx.textLayout.elements.ListElement;
public class GameObject extends MovieClip
{
static public var list:Vector.<GameObject> = new Vector.<GameObject>;
protected var hitBox:Sprite;
public var target:MovieClip;
public function GameObject()
{
target=this;
list.push(this);
}
public function update():void
{
}
public function collision(typesColliding:Array, $target:DisplayObject = null):GameObject
{
if($target == null)
$target = target;
for (var i:int = list.length - 1; i >= 0; i--)
{
var item:GameObject = list[i], found:Boolean = false;
for (var f:int = typesColliding.length - 1; f >= 0; f--)
{
if (item is typesColliding[f])
{
found = true;
break;
}
}
if (found && $target.hitTestObject(item.target) && this != item)
{
return item;
}
}
return null;
}
public function moveBy(typesColliding:Array, $x:Number = 0, $y:Number = 0, $target:DisplayObject = null):void
{
var $collision:GameObject;
x += $x;
if (($collision = collision(typesColliding, $target)) != null)
{
x -= $x;
onCollideX($collision);
}
y += $y;
if (($collision = collision(typesColliding, $target)) != null)
{
y -= $y;
onCollideY($collision);
}
}
public function onCollideX($collision:GameObject):void
{
}
public function onCollideY($collision:GameObject):void
{
}
public function getType($class:Class):Vector.<GameObject>
{
var $list:Vector.<GameObject> = new Vector.<GameObject>;
for (var i:int = 0; i < list.length; i++)
{
if (list[i] is $class)
{
$list.push(list[i]);
}
}
return $list;
}
public function destroy():void
{
var indexOf:int = list.indexOf(this);
if (indexOf > -1)
list.splice(indexOf, 1);
if (parent)
parent.removeChild(this);
trace("removing item: "+this+" list: " + list.length + ": " + list);
}
}
}
Any help would be appreciated, thank you.
Changing radius of vision to the cone of vision simply requires computing (after checking the distance) the angle between the direction enemy is facing and the player. If this angle is smaller then some T, then it is in the cone of vision of angle 2T (due to symmetry).
This obviously ignores any walls/obstacles that should limit vision, but it should give you the general idea.

Positioning a movieclip onto another movieclip

I'm creating a game where if you hit a zombie the zombie dies and his head is sent back in the direction you hit. I have two movieclips the zombie and the zombie head. Once the zombie is hit it will play its dying animation and remove itself and at the same time the zombie head will be added to the dying zombie and be blown back. I have done the code for the hittest and the zombie dying and respawning but I can't seem to position and add the head to the dying zombie when it is hit. How can I do this. I thought it will be like this, I added this in the PlayDeathAnimation function in the zombie class but did not work:
for (var i=0; i < MovieClip(parent).zombies.length; ++i)
{
var zh = new ZombieHead();
zh.x = MovieClip(parent).zombies[i].x;
zh.y = MovieClip(parent).zombies[i].y;
zh.rotation = MovieClip(parent).zombies[i].rotation;
addChild(zh);
}
I have 4 classes
Player
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
import flash.display.Graphics;
import flash.utils.setTimeout;
public class Player extends MovieClip
{
//Player Setting
var walkSpeed:Number = 4;
var walkRight:Boolean = false;
var walkLeft:Boolean = false;
var walkUp:Boolean = false;
var walkDown:Boolean = false;
var attacking:Boolean = false;
var attackRange:int = 100;
var attackAngle:int = 30;
public function Player()
{
stage.addEventListener(KeyboardEvent.KEY_DOWN,walk);
addEventListener(Event.ENTER_FRAME,Update);
stage.addEventListener(KeyboardEvent.KEY_UP,stopWalk);
stage.addEventListener(MouseEvent.CLICK,attack);
// The lines below draw a preview of your attack area
graphics.beginFill(0x00ff00, 0.2);
graphics.lineTo(attackRange*Math.cos((rotation-attackAngle)/180*Math.PI),attackRange*Math.sin((rotation-attackAngle)/180*Math.PI));
graphics.lineTo(attackRange*Math.cos((rotation+attackAngle)/180*Math.PI),attackRange*Math.sin((rotation+attackAngle)/180*Math.PI));
graphics.endFill();
}
function walk(event:KeyboardEvent)
{
//When Key is Down
if (event.keyCode == 68)
{
walkRight = true;
}
if (event.keyCode == 87)
{
walkUp = true;
}
if (event.keyCode == 65)
{
walkLeft = true;
}
if (event.keyCode == 83)
{
walkDown = true;
}
}
function Update(event:Event)
{
//if attacking is true then key moves are false;
if ((attacking == true))
{
walkRight = false;
walkLeft = false;
walkUp = false;
walkDown = false;
// see if the zombie is in the cone
for (var i:int=MovieClip(parent).zombies.length-1; i>=0; i--)
{
if (inAttackCone(MovieClip(parent).zombies[i]))
{
if (hitTestObject(MovieClip(parent).zombies[i]))
{
//attacking = true;
MovieClip(parent).zombies[i].zombieDead = true;
}
}
}
}
else if ((attacking == false))
{
//Else if attacking is false then move and rotate to mouse;
var dx = parent.mouseX - x;
var dy = parent.mouseY - y;
var angle = Math.atan2(dy,dx) / Math.PI * 180;
rotation = angle;
if ((walkRight == true))
{
x += walkSpeed;
gotoAndStop(2);
}
if ((walkUp == true))
{
y -= walkSpeed;
gotoAndStop(2);
}
if ((walkLeft == true))
{
x -= walkSpeed;
gotoAndStop(2);
}
if ((walkDown == true))
{
y += walkSpeed;
gotoAndStop(2);
}
}
}
//Calculate the distance between the two
public function distanceBetween(player:MovieClip,zombies:MovieClip):Number
{
for (var i:int=MovieClip(parent).zombies.length-1; i>=0; i--)
{
var dx:Number = x - MovieClip(parent).zombies[i].x;
var dy:Number = y - MovieClip(parent).zombies[i].y;
}
return Math.sqrt(((dx * dx) + dy * dy));
}
public function angleDifference(a:Object, b:Object):Number
{
var dx:Number = b.x - a.x;
var dy:Number = b.y - a.y;
var ang:Number = (a.rotation/180*Math.PI)-Math.atan2(dy, dx);
while (ang>Math.PI)
{
ang -= 2 * Math.PI;
}
while (ang<-Math.PI)
{
ang += 2 * Math.PI;
}
return Math.abs(ang*180/Math.PI);
}
function inAttackCone(enemy:MovieClip):Boolean
{
var distance:Number = distanceBetween(this,enemy);
distance -= enemy.width / 2;// account for the enemy's size
if (distance < attackRange)
{
// In range, check angle
if (angleDifference(this,enemy)<attackAngle)
{
return true;
}
}
return false;
}
function stopWalk(event:KeyboardEvent)
{
if ((attacking == false))
{
if (event.keyCode == 68)
{
event.keyCode = 0;
walkRight = false;
gotoAndStop(1);
}
if (event.keyCode == 87)
{
event.keyCode = 0;
walkUp = false;
gotoAndStop(1);
}
if (event.keyCode == 65)
{
event.keyCode = 0;
walkLeft = false;
gotoAndStop(1);
}
if (event.keyCode == 83)
{
event.keyCode = 0;
walkDown = false;
gotoAndStop(1);
}
}
}
function attack(event:MouseEvent)
{
if ((attacking == false))
{
attacking = true;
gotoAndStop(3);
}
}
}
}
Zombies
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.geom.Point;
public class Zombie extends MovieClip
{
var walkSpeed:Number = 2;
var target:Point;
public var zombieDead:Boolean = false;
public function Zombie()
{
//set target location of Zombie
target = new Point(Math.random() * 500,Math.random() * 500);
}
function loop()
{
if (zombieDead == true)
{
playDeathAnimation();
}
else if (zombieDead == false)
{
gotoAndStop(1);
//Point Zombie at its target
var dx = MovieClip(root).Player01.x - x;
var dy = MovieClip(root).Player01.y - y;
var angle = Math.atan2(dy,dx) / Math.PI * 180;
rotation = angle;
//Move in the direction the zombie is facing
x = x+Math.cos(rotation/180*Math.PI)*walkSpeed;
y = y+Math.sin(rotation/180*Math.PI)*walkSpeed;
//Calculate the distance to target
var hyp = Math.sqrt((dx*dx)+(dy*dy));
if (hyp<5)
{
target.x = Math.random() * 500;
target.y = Math.random() * 500;
}
}
}
public function playDeathAnimation()
{
gotoAndStop(2);
}
public function deathAnimationFinishedCallback()
{
for (var i=0; i < MovieClip(parent).zombies.length; ++i)
{
if (MovieClip(parent).zombies[i] == this)
{
MovieClip(parent).zombies.splice(i, 1);
break;
}
}
MovieClip(parent).removeChild(this);
}
}
}
Document Class
package
{
import flash.display.MovieClip;
import flash.events.Event;
public class Game extends MovieClip
{
public var zombies:Array;
public function Game()
{
addEventListener(Event.ENTER_FRAME, update);
zombies = new Array();
}
public function update(e:Event)
{
//Only spawn a Zombie if there are less than number
if (numChildren < 4)
{
//Make a new instance of the Zombie.
var Z = new Zombie();
addChild(Z);
//Position and rotate the zombie
Z.x = Math.random() * stage.stageWidth;
Z.y = Math.random() * stage.stageHeight;
Z.rotation = Math.random() * 360;
zombies.push(Z);
}
for (var count = 0; count<zombies.length; count ++)
{
zombies[count].loop();
}
}
}
}
Zombie Head
package
{
import flash.display.MovieClip;
import flash.events.Event;
public class ZombieHead extends MovieClip
{
var headSpeed:Number = -30;
var friction:Number = 0.9;
public function ZombieHead()
{
// constructor code
addEventListener(Event.ENTER_FRAME,Update);
}
function Update(event:Event)
{
x = x+Math.cos(rotation/180*Math.PI)*headSpeed;
y = y+Math.sin(rotation/180*Math.PI)*headSpeed;
headSpeed *= friction;
if (headSpeed > -0.00001)
{
removeEventListener(Event.ENTER_FRAME,Update);
parent.removeChild(this);
}
else if (x<0 || x > 550 || y < 0 || y > 400)
{
removeEventListener(Event.ENTER_FRAME,Update);
parent.removeChild(this);
}
}
}
}

Resources