I am trying to iterate through this array of objects, but I keep getting "; expected" when I try and make a for loop to do so within the constructor.
public class EletronicStore {
public EletronicStore() {
Object[] obj = new Object[9];
Desktop d1 = new Desktop(3.5, 8, 500, false);
Desktop d2 = new Desktop(3, 16, 250, true);
Desktop d3 = new Desktop(4.3, 32, 500, true);
Laptop l1 = new Laptop(3.1, 32, 500, true, 15);
Laptop l2 = new Laptop(2.5, 8, 250, false, 13);
Laptop l3 = new Laptop(3.0, 16, 250, true, 15);
Fridge f1 = new Fridge(15.6, true, "Gray");
Fridge f2 = new Fridge(10.5, false, "White");
Fridge f3 = new Fridge(23, true, "Stainless Steel");
obj[0] = d1.toString();
obj[1] = d2.toString();
obj[2] = d3.toString();
obj[3] = l1.LaptoString();
obj[4] = l2.LaptoString();
obj[5] = l3.LaptoString();
obj[6] = f1.FridgetoString();
obj[7] = f2.FridgetoString();
obj[8] = f3.FridgetoString();
public void printStock(){
for (int i = 0; i < 9; i++){ \\ here it says ; expected
System.out.println(obj[i]);
}
}
}
}
The issue here is not with the for loop, it is that you are defining a new function inside the constructor
If you remove the 'public void printStock() {' and its closing brace and leave the for loop as is, it should work as you expect.
If you need the printStock function it will have to be defined outside the constructor, but it will not have access to your object array which is defined in the local scope of the constructor.
Related
I'm struggling to solve how to set opacity/transparency/alpha of colors in charts using Apache POI. Using the XDDF classes, there seems to be no way to do this. The Documentation of XDDFColor has no way to set this value when creating this object. The only thing that I thought may have worked was accessing the underlying CTHslColor from the XDDFColor as follows.
XDDFColor xddfColor = XDDFColor.from(PresetColor.LIGHT_GREEN);
CTColor container = xddfColor.getColorContainer();
CTHslColor hslColor = container.addNewHslClr();
CTPositiveFixedPercentage p = hslColor.addNewAlpha();
p.setVal(50000);
XDDFChartData.Series series = data.getSeries(2);
XDDFSolidFillProperties fill = new XDDFSolidFillProperties(xddfColor);
XDDFLineProperties line = new XDDFLineProperties();
line.setFillProperties(fill);
XDDFShapeProperties properties = series.getShapeProperties();
if (properties == null) {
properties = new XDDFShapeProperties();
}
properties.setLineProperties(line);
series.setShapeProperties(properties);
series.setFillProperties(fill);
While the color is correctly set in the chart, the transparency does not work. Is there any way to be able to set the fill color transparency for an Area Chart using POI?
The constructor XDDFSolidFillProperties(XDDFColor) creates a CTSolidColorFillProperties having a CTPresetColor corresponding to the given XDDFColor if that XDDFColor is instanceof XDDFColorPreset. And after that you should set the alpha, instead of manipulating the XDDFColor before. Also you should set fill properties as well as line properties to the XDDFShapeProperties and those to the series then. So:
private static void solidFillSeries(XDDFChartData data, int index, PresetColor color, int alpha) {
XDDFSolidFillProperties fill = new XDDFSolidFillProperties(XDDFColor.from(color));
org.openxmlformats.schemas.drawingml.x2006.main.CTSolidColorFillProperties ctSolidColorFillProperties =
(org.openxmlformats.schemas.drawingml.x2006.main.CTSolidColorFillProperties)fill.getXmlObject();
org.openxmlformats.schemas.drawingml.x2006.main.CTPresetColor ctPresetColor = ctSolidColorFillProperties.getPrstClr();
org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveFixedPercentage ctPositiveFixedPercentage = ctPresetColor.addNewAlpha();
ctPositiveFixedPercentage.setVal(alpha);
XDDFChartData.Series series = data.getSeries(index);
XDDFShapeProperties properties = series.getShapeProperties();
if (properties == null) {
properties = new XDDFShapeProperties();
}
properties.setFillProperties(fill);
XDDFLineProperties line = new XDDFLineProperties();
line.setFillProperties(fill);
properties.setLineProperties(line);
series.setShapeProperties(properties);
}
Complete example:
import java.io.FileOutputStream;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xddf.usermodel.*;
import org.apache.poi.xddf.usermodel.chart.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class CreateExcelXDDFAreaChart {
public static void main(String[] args) throws Exception {
try (XSSFWorkbook document = new XSSFWorkbook()) {
XSSFSheet sheet = document.createSheet("SurfaceChart");
// create the data
String[] categories = new String[] { "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9" };
Double[] values1 = new Double[] { 10d, 20d, 10d, 15d, 12d, 20d, 10d, 18d, 19d };
Double[] values2 = new Double[] { 20d, 10d, 15d, 20d, 11d, 17d, 18d, 20d, 10d };
Double[] values3 = new Double[] { 14.5d, 14d, 13.5d, 13d, 12.5d, 12d, 11.5d, 11d, 10.5d };
int r = 0;
for (String cat : categories) {
sheet.createRow(r).createCell(0).setCellValue(cat);
sheet.getRow(r).createCell(1).setCellValue(values1[r]);
sheet.getRow(r).createCell(2).setCellValue(values2[r]);
sheet.getRow(r).createCell(3).setCellValue(values3[r]);
r++;
}
// create the chart
XSSFDrawing drawing = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 5, 0, 20, 30);
XDDFChart chart = drawing.createChart(anchor);
// create data sources
int numOfPoints = categories.length;
XDDFDataSource<String> categoriesData = XDDFDataSourcesFactory.fromStringCellRange(sheet, new CellRangeAddress(0, numOfPoints-1, 0, 0));
XDDFNumericalDataSource<Double> valuesData1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, numOfPoints-1, 1, 1));
XDDFNumericalDataSource<Double> valuesData2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, numOfPoints-1, 2, 2));
XDDFNumericalDataSource<Double> valuesData3 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, numOfPoints-1, 3, 3));
// area chart
XDDFCategoryAxis categoryAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
XDDFValueAxis valueAxis = chart.createValueAxis(AxisPosition.LEFT);
valueAxis.setCrosses(AxisCrosses.AUTO_ZERO);
XDDFChartData data = chart.createData(ChartTypes.AREA, categoryAxis, valueAxis);
XDDFChartData.Series series = data.addSeries(categoriesData, valuesData1);
series.setTitle("Series 1", null);
series = data.addSeries(categoriesData, valuesData2);
series.setTitle("Series 2", null);
series = data.addSeries(categoriesData, valuesData3);
series.setTitle("Series 3", null);
chart.plot(data);
// set legend
XDDFChartLegend legend = chart.getOrAddLegend();
legend.setPosition(LegendPosition.BOTTOM);
solidFillSeries(data, 0, PresetColor.RED, 50000);
solidFillSeries(data, 1, PresetColor.GREEN, 50000);
solidFillSeries(data, 2, PresetColor.BLUE, 50000);
// Write the output to a file
try (FileOutputStream fileOut = new FileOutputStream("./CreateExcelXDDFAreaChart.xlsx")) {
document.write(fileOut);
}
}
}
private static void solidFillSeries(XDDFChartData data, int index, PresetColor color, int alpha) {
XDDFSolidFillProperties fill = new XDDFSolidFillProperties(XDDFColor.from(color));
org.openxmlformats.schemas.drawingml.x2006.main.CTSolidColorFillProperties ctSolidColorFillProperties =
(org.openxmlformats.schemas.drawingml.x2006.main.CTSolidColorFillProperties)fill.getXmlObject();
org.openxmlformats.schemas.drawingml.x2006.main.CTPresetColor ctPresetColor = ctSolidColorFillProperties.getPrstClr();
org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveFixedPercentage ctPositiveFixedPercentage = ctPresetColor.addNewAlpha();
ctPositiveFixedPercentage.setVal(alpha);
XDDFChartData.Series series = data.getSeries(index);
XDDFShapeProperties properties = series.getShapeProperties();
if (properties == null) {
properties = new XDDFShapeProperties();
}
properties.setFillProperties(fill);
XDDFLineProperties line = new XDDFLineProperties();
line.setFillProperties(fill);
properties.setLineProperties(line);
series.setShapeProperties(properties);
}
}
Hint: The value of the CTPositiveFixedPercentagealpha is percentage in units of 1000th (thousandth) percent. So it is from 0 to 100000 and 50000 is 50%.
I don't really know how to explain this but I will try my best
so I have a Card class in the file card.js that look like this:
class card {
constructor(name = "", portrait = "", bloodCost = 0, boneCost = 0, power = 0, health = 1, sigilList = []) {
this.name = name
this.portrait = portrait;
this.bloodCost = bloodCost;
this.boneCost = boneCost;
this.power = power;
this.health = health;
this.sigilList = sigilList;
}
attack(sigilList = [], board = [], oppositeCard = new card(), scale = 0) {
var oppositeCardHealth = 0
if (oppositeCard == blank) {
scale += this.power;
}
else {
oppositeCardHealth += this.power;
}
return [scale, oppositeCardHealth];
};
var wolf = new card("Wolf", ":wolf:", 2, 0, 3, 2);
module.exports = { wolf };
}
And a 'main.js' file like this:
const cardLib = require("./lib/card");
var broad = [cardLib.wolf, cardLib.wolf]
broad[0].health -= 2;
console.log(broad);
So what I want to do is only changing the health of the wolf in broad[0] with out changing the other one health. Which mean the program should return something like this:
[
card {
name: 'Wolf',
portrait: ':wolf:',
bloodCost: 2,
boneCost: 0,
power: 3,
health: 0,
sigilList: []
},
card {
name: 'Wolf',
portrait: ':wolf:',
bloodCost: 2,
boneCost: 0,
power: 3,
health: 2,
sigilList: []
}
]
This statement:
var broad = [cardLib.wolf, cardLib.wolf]
Put's two references to the exact same wolf object in your array. So, naturally, if you change one, the other will appear changed also because both spots in the array point at the exact same object.
If you want two separate, independent objects in the array, then you have to create two separate objects by creating a separate card. To do that from outside that file, it would be best to export the Card constructor so you can call it and create a separate card to put into the array. Another option would be to add a .copy() method to your Card object so you can create a copy of an existing object.
Here's an example of a .copy() method:
class card {
constructor(name = "", portrait = "", bloodCost = 0, boneCost = 0, power = 0, health = 1, sigilList = []) {
this.name = name
this.portrait = portrait;
this.bloodCost = bloodCost;
this.boneCost = boneCost;
this.power = power;
this.health = health;
this.sigilList = sigilList;
}
attack(sigilList = [], board = [], oppositeCard = new card(), scale = 0) {
var oppositeCardHealth = 0
if (oppositeCard == blank) {
scale += this.power;
} else {
oppositeCardHealth += this.power;
}
return [scale, oppositeCardHealth];
}
copy() {
let newCard = new card(
this.name,
this.portrait,
this.bloodCost,
this.boneCost,
this.power,
this.health,
this.sigilList.slice(0);
)
return newCard;
}
}
let wolf = new card("Wolf", ":wolf:", 2, 0, 3, 2);
module.exports = { wolf };
Which you can then use like this:
let broad = [cardLib.wolf, cardLib.wolf.copy()];
This implementation assumes that none of the instance variables except sigilList are objects that have to be copied themselves in order to be separate and that the sigilList array can be shallow copied with .slice(0) in order to be independent.
In your current code, wolf is a specific instance of a card. Your array has two references to the same object, so changing one of them will change them "both".
One approach could be to not hold a wolf variable, but instead provide a function to create such a wolf card:
// card.js:
class card {
// constructor and attack unchanged, removed for brevity's sake
}
var wolf = () => new card("Wolf", ":wolf:", 2, 0, 3, 2);
module.exports = { wolf };
// main.js:
const cardLib = require("./lib/card");
var broad = [cardLib.wolf(), cardLib.wolf()]; // wolf is a function that creates a a card
broad[0].health -= 2;
console.log(broad);
I can't perform multiple delette from my listbox although I made the listbox mutiselect Why ??
I need your help . You can see the full Script down there.
(function(){
$.win = new Window("palette");
var win = $.win;
win.orientation = "column";
win.alignChildren = ["center", "top"];
win.spacing = 10;
win.margins = 16;
var listbox1 = win.add("listbox", undefined, undefined, { name: "listbox1", multiselect: true, columnTitles: "Max", showHeaders: true });
listbox1.preferredSize.width = 136;
listbox1.preferredSize.height = 208;
var button1 = win.add("button", undefined, undefined, { name: "button1" });
button1.text = "Search";
var button2 = win.add("button", undefined, undefined, { name: "button2" });
button2.text = "Delete";
win.show();
var myNewArray = [];
button1.onClick = function Search() {
var compsArray = new Array();
var myProj = app.project;
myNewArray = [];
listbox1.removeAll();
for (var i = 1; i <= myProj.numItems; i++) {
if (myProj.item(i) instanceof CompItem) {
myNewArray = compsArray[compsArray.length] = myProj.item(i);
listbox1.add("item", myNewArray.name);
}
}
}
button2.onClick = function deletecomps() {
for (var s = 1; s <= app.project.numItems; s ++) {
if ((app.project.item(s) instanceof CompItem) && (app.project.item(s).name.match(listbox1.selection))) {
myComp = app.project.item(s);
break;
}
}
app.project.item(s).remove ();
}
})();
You can see an image to clarify the script in AE
Your problem is that listbox1.selection in line 34
if ((app.project.item(s) instanceof CompItem) && (app.project.item(s).name.match(listbox1.selection))) {
is an array, and you're trying to match it to a string returned by app.project.item(s).name which is never going to match.
Also, what are you trying to achieve with the lines
myComp = app.project.item(s);
break;
Here's the onClick function, but it works. It loops through the selection, and looks for a matching project item, based on the text of the listbox matching the comp's name. This is dangerous, because identical comp names would create false positives. I strongly suggest you don't use this technique in production code, because it will definitely cause problems for your users.
Also I'd turn the part wherre you populate the list into a separate function, and call it after you click delete, so that the list is refreshed, because at the moment the list stays the same, even after the comp is deleted.
button2.onClick = function deletecomps() {
for (var b= 0; b < listbox1.selection.length; b++){
for (var s = 1; s <= app.project.numItems; s ++) {
if ((app.project.item(s) instanceof CompItem) && (app.project.item(s).name.match(listbox1.selection[b].text))) {
app.project.item(s).remove ();
}
}
}
}
I am trying remove 3mm bleed size from pdf. by using below criteria
My source file is Source file
I am using below code to trim left and right
public void TrimLeftandRight(string sourceFilePath, string outputFilePath)
{
PdfReader pdfReader = new PdfReader(sourceFilePath);
float width = (float)GetPDFwidth(sourceFilePath);
float height = (float)GetPDFHeight(sourceFilePath);
float widthTo_Trim = iTextSharp.text.Utilities.MillimetersToPoints(3);
PdfRectangle rectrightside = new PdfRectangle(0, 0, width - widthTo_Trim, height);
PdfRectangle rectLeftside = new PdfRectangle(widthTo_Trim, 0, width, height);
// int[] pagealignment = new int[] { 8, 1, 2, 7, 6, 3, 4, 5 };
int[] pagealignment = new int[] { 6, 1, 2, 5, 4, 3 };
using (var output = new FileStream(outputFilePath, FileMode.CreateNew, FileAccess.Write))
{
// Create a new document
Document doc = new Document();
// Make a copy of the document
PdfSmartCopy smartCopy = new PdfSmartCopy(doc, output);
// Open the newly created document
doc.Open();
// Loop through all pages of the source document
for (int i = 1; i <= pdfReader.NumberOfPages; i++)
{
// Get a page
var page = pdfReader.GetPageN(i);
// Apply the rectangle filter we created
switch (i)
{
case 6:
page.Put(PdfName.CROPBOX, rectLeftside);
page.Put(PdfName.MEDIABOX, rectrightside);
break;
case 2:
page.Put(PdfName.MEDIABOX, rectrightside);
break;
case 4:
page.Put(PdfName.MEDIABOX, rectLeftside);
break;
case 1:
page.Put(PdfName.MEDIABOX, rectLeftside);
break;
case 5:
page.Put(PdfName.MEDIABOX, rectrightside);
// page.Put(PdfName.CROPBOX, rectLeftside);
break;
case 3:
page.Put(PdfName.CROPBOX, rectLeftside);
page.Put(PdfName.MEDIABOX, rectrightside);
break;
}
// Copy the content and insert into the new document
var copiedPage = smartCopy.GetImportedPage(pdfReader, i);
smartCopy.AddPage(copiedPage);
}
// Close the output document
smartCopy.Close();
doc.Close();
doc.Dispose();
}
}
the output of above code produces
Trimmed left and right file
and I used below code to merge trimmed files
public void CreategateFinalOutput(string inputfile)
{
double widthinpoints = iTextSharp.text.Utilities.MillimetersToPoints(897);
string onlyfilename = Path.GetFileName(inputfile);
// string originalfilename = Server.MapPath("~/Uploads/" + onlyfilename);
int Noofpagesinpdf = GetNoofpagesofpdf(inputfile);
// var a3doc = new Document(PageSize.A3.Rotate(), 0, 0, 0, 0);
double originalwidth = GetPDFwidth(inputfile);
float widthTo_Trim = iTextSharp.text.Utilities.MillimetersToPoints(3);
double width = (GetPDFwidth(inputfile) * 3);
width = widthinpoints;
double height = GetPDFHeight(inputfile);
var a3reader = new PdfReader(inputfile);
var a3doc = new Document(new Rectangle((float)width, (float)height));
var a3writer = PdfWriter.GetInstance(a3doc, new FileStream(Server.MapPath("~/RP/" + onlyfilename), FileMode.Create));
a3doc.Open();
var a3cb = a3writer.DirectContent;
PdfImportedPage page;
int totalPages = a3reader.NumberOfPages;
// int[] pagealignment = new int[] { 8, 1, 2, 7, 6, 3, 4, 5 };
int[] pagealignment = new int[] { 5, 6, 1, 2, 3, 4 };
int iteration = 1;
for (int i = 1; i <= totalPages; i++)
{
a3doc.NewPage();
var a3size = new Document(new Rectangle((float)width, (float)height));
//new code
int fistpage = 0;
int secpage = 0;
int thirdpage = 0;
switch (iteration)
{
case 1:
fistpage = 5;
secpage = 6;
thirdpage = 1;
break;
case 2:
fistpage = 2;
secpage = 3;
thirdpage = 4;
break;
}
double trimwidth = iTextSharp.text.Utilities.MillimetersToPoints(3);
page = a3writer.GetImportedPage(a3reader, fistpage);
double pagewidth = page.Width;
a3cb.AddTemplate(page, 0, 0);
i++;
page = a3writer.GetImportedPage(a3reader, secpage);
double pagewidtha = page.Width;
a3cb.AddTemplate(page, (float)(pagewidtha), 0);
i++;
page = a3writer.GetImportedPage(a3reader, thirdpage);
double pagewidthaThird = page.Width;
// a3cb.AddTemplate(page, (int)(a3size.Width / 2), 0); //commented
a3cb.AddTemplate(page, (float)(pagewidthaThird + pagewidth), 0);
iteration++;
a3doc.Close();
}
}
When i merged pdf by using above code the out put is not as per desire
Final output
Here we have removed borders of page 5 and 6 but when we merged there is border appearing .
You can see it downloading pdfs.. apologies for a such a big code. the help will be highly appreciated
I request to download pdfs and check pdfs for better views
I'm referring to the official example on Phaser.io site, but have copied it here for reference below. What I want, and repeatedly fail to achieve is that the moving (with keyboard keys) starfield sprite would not collide with other vegies sprites.
I did go through the docs and looked here on SO and their forum, and it seems that the solutions should be easy enough; to just put the following code in the update() function:
game.world.bringToTop(sprite);
But, for some reason this is not working for me, so please tell me what I'm doing wrong.
var game = new Phaser.Game(800, 600, Phaser.CANVAS, 'phaser-example', { preload: preload, create: create, update: update });
function preload() {
game.load.image('sky', 'assets/skies/sky4.png');
game.load.image('starfield', 'assets/misc/starfield.jpg');
game.load.spritesheet('veggies', 'assets/sprites/fruitnveg64wh37.png', 64, 64);
}
var sprite;
var cursors;
var veggies;
function create() {
game.add.image(0, 0, 'sky');
// Enable p2 physics
game.physics.startSystem(Phaser.Physics.P2JS);
// Make things a bit more bouncey
game.physics.p2.defaultRestitution = 0.8;
// Add a sprite
sprite = game.add.tileSprite(300, 450, 200, 50, 'starfield');
// Enable if for physics. This creates a default rectangular body.
game.physics.p2.enable(sprite);
veggies = game.add.group();
veggies.enableBody = true;
veggies.physicsBodyType = Phaser.Physics.P2JS;
var vegFrames = [ 1, 3, 4, 8 ];
for (var i = 0; i < 10; i++)
{
var veg = veggies.create(game.world.randomX, game.world.randomY, 'veggies', game.rnd.pick(vegFrames));
veg.body.setCircle(26);
}
text = game.add.text(20, 20, 'move with arrow keys', { fill: '#ffffff' });
cursors = game.input.keyboard.createCursorKeys();
}
function update() {
sprite.body.setZeroVelocity();
game.world.bringToTop(veggies);
if (cursors.left.isDown)
{
sprite.body.moveLeft(400);
sprite.tilePosition.x -= 8;
}
else if (cursors.right.isDown)
{
sprite.body.moveRight(400);
sprite.tilePosition.x += 8;
}
if (cursors.up.isDown)
{
sprite.body.moveUp(400);
sprite.tilePosition.y -= 8;
}
else if (cursors.down.isDown)
{
sprite.body.moveDown(400);
sprite.tilePosition.y += 8;
}
}
edit: Solution which worked in the end thanks to SirSandman's answer:
var game = new Phaser.Game(800, 600, Phaser.AUTO, 'phaser-example', { preload: preload, create: create, update: update, render: render });
function preload() {
game.load.image('stars', 'assets/misc/starfield.jpg');
game.load.spritesheet('ship', 'assets/sprites/humstar.png', 32, 32);
game.load.image('panda', 'assets/sprites/spinObj_01.png');
game.load.image('sweet', 'assets/sprites/spinObj_06.png');
}
var ship;
var starfield;
var cursors;
function create() {
// Enable P2
game.physics.startSystem(Phaser.Physics.P2JS);
// Turn on impact events for the world, without this we get no collision callbacks
game.physics.p2.setImpactEvents(true);
game.physics.p2.restitution = 0.8;
// Create our collision groups. One for the player, one for the pandas
var playerCollisionGroup = game.physics.p2.createCollisionGroup();
var pandaCollisionGroup = game.physics.p2.createCollisionGroup();
// This part is vital if you want the objects with their own collision groups to still collide with the world bounds
// (which we do) - what this does is adjust the bounds to use its own collision group.
game.physics.p2.updateBoundsCollisionGroup();
starfield = game.add.tileSprite(0, 0, 800, 600, 'stars');
starfield.fixedToCamera = true;
var pandas = game.add.group();
pandas.enableBody = true;
pandas.physicsBodyType = Phaser.Physics.P2JS;
for (var i = 0; i < 4; i++)
{
var panda = pandas.create(game.world.randomX, game.world.randomY, 'panda');
panda.body.setRectangle(40, 40);
// Tell the panda to use the pandaCollisionGroup
panda.body.setCollisionGroup(pandaCollisionGroup);
// Pandas will collide against themselves and the player
// If you don't set this they'll not collide with anything.
// The first parameter is either an array or a single collision group.
panda.body.collides(pandaCollisionGroup);
panda.body.velocity.x = 500;
panda.body.velocity.y = 500;
}
// Create our ship sprite
ship = game.add.sprite(200, 200, 'ship');
ship.scale.set(2);
ship.smoothed = false;
ship.animations.add('fly', [0,1,2,3,4,5], 10, true);
ship.play('fly');
game.physics.p2.enable(ship, false);
ship.body.setCircle(28);
ship.body.fixedRotation = true;
// Set the ships collision group
ship.body.setCollisionGroup(playerCollisionGroup);
// The ship will collide with the pandas, and when it strikes one the hitPanda callback will fire, causing it to alpha out a bit
// When pandas collide with each other, nothing happens to them.
game.camera.follow(ship);
cursors = game.input.keyboard.createCursorKeys();
}
function hitPanda(body1, body2) {
// body1 is the space ship (as it's the body that owns the callback)
// body2 is the body it impacted with, in this case our panda
// As body2 is a Phaser.Physics.P2.Body object, you access its own (the sprite) via the sprite property:
body2.sprite.alpha -= 0.1;
}
function update() {
ship.body.setZeroVelocity();
if (cursors.left.isDown)
{
ship.body.moveLeft(200);
}
else if (cursors.right.isDown)
{
ship.body.moveRight(200);
}
if (cursors.up.isDown)
{
ship.body.moveUp(200);
}
else if (cursors.down.isDown)
{
ship.body.moveDown(200);
}
if (!game.camera.atLimit.x)
{
starfield.tilePosition.x += (ship.body.velocity.x * 16) * game.time.physicsElapsed;
}
if (!game.camera.atLimit.y)
{
starfield.tilePosition.y += (ship.body.velocity.y * 16) * game.time.physicsElapsed;
}
}
function render() {
game.debug.text('Collide with the Pandas!', 32, 32);
}
I P2 you have to set the Collisiongroups in contrast to arcarde.
I think you have to set a collisiongroup for the sprite like that:
var veggCollisionGroup = game.physics.p2.createCollisionGroup();
and then define with which other groups this group shell collide like that in the Loop:
veggies.body.setCollisionGroup(veggCollisionGroup);
veggies.body.collides(veggCollisionGroup);
And then the your tilesprite should collide with your other tilesprites.
Source:
http://phaser.io/examples/v2/p2-physics/collision-groups
if i should be wrong you will find your answer in the examples. :)