Box2d Bounding Box Without Force - static

Currently, the Cocos2d-Box2d project is using a b2Vec2 to create a Bounding Box for the edge of the game. Because of this, the bounding Box isn't affecting kinematic bodies, which are bodies that aren't affected by force(meaning that the bodies will usually fly off the screen). I'm trying to see if there's a way to either make the kinematic body connect with the screen. If not, i would appreciate it if someone explain to me how I should make a boundingbox with static bodies around the corner of the screens.

Here is two ways...Try any one
// Method - 1
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0, 0);
b2Body *mGroundBody ;
mGroundBody = self.world->CreateBody(&groundBodyDef);
NSString *strId = #"Ground Body";
mGroundBody->SetUserData(strId);
b2EdgeShape groundBox;
//bottom
groundBox.Set(b2Vec2(0.0f,0.0f), b2Vec2(mS.width/PTM_RATIO,0.0f));
mGroundBody->CreateFixture(&groundBox,0);
// top
groundBox.Set(b2Vec2(0,mS.height/PTM_RATIO), b2Vec2(mS.width/PTM_RATIO, mS.height/PTM_RATIO));
mGroundBody->CreateFixture(&groundBox,0);
// left
groundBox.Set(b2Vec2(0,mS.height/PTM_RATIO), b2Vec2(0,0));
mGroundBody->CreateFixture(&groundBox,0);
// right
groundBox.Set(b2Vec2(mS.width/PTM_RATIO,mS.height/PTM_RATIO), b2Vec2(mS.width/PTM_RATIO,0));
mGroundBody->CreateFixture(&groundBox,0);
// Method - 2
//create 4 box2d walls...
float bW = (IS_IPAD) ? (8) : 2 ;
//top
{
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;
bodyDef.position.Set((mS.width*0.5f)/PTM_RATIO, (mS.height)/PTM_RATIO);
bodyDef.linearDamping = 0.0f;
bodyDef.angularDamping = 0.0f;
bodyDef.userData = strId ;
b2PolygonShape box;
box.SetAsBox( ((mS.width*0.5f)/PTM_RATIO), (bW)/PTM_RATIO);
b2FixtureDef fixDef;
fixDef.shape = &box;
fixDef.density = 1.0f;
fixDef.friction = 0.1f;
fixDef.restitution = 1.0f;
fixDef.isSensor = false;
b2Body *topBody = self.world->CreateBody(&bodyDef);
topBody->CreateFixture(&fixDef);
}
//bottom
{
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;
bodyDef.position.Set((mS.width*0.5f)/PTM_RATIO, 0);
bodyDef.linearDamping = 0.0f;
bodyDef.angularDamping = 0.0f;
bodyDef.userData = strId ;
b2PolygonShape box;
box.SetAsBox( ((mS.width*0.5f)/PTM_RATIO), (bW)/PTM_RATIO);
b2FixtureDef fixDef;
fixDef.shape = &box;
fixDef.density = 1.0f;
fixDef.friction = 0.1f;
fixDef.restitution = 1.0f;
fixDef.isSensor = false;
b2Body *topBody = self.world->CreateBody(&bodyDef);
topBody->CreateFixture(&fixDef);
}
//left
{
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;
bodyDef.position.Set(0, (mS.height*0.5f)/PTM_RATIO);
bodyDef.linearDamping = 0.0f;
bodyDef.angularDamping = 0.0f;
bodyDef.userData = strId ;
b2PolygonShape box;
box.SetAsBox( ((bW)/PTM_RATIO), (mS.height*0.5f)/PTM_RATIO);
b2FixtureDef fixDef;
fixDef.shape = &box;
fixDef.density = 1.0f;
fixDef.friction = 0.1f;
fixDef.restitution = 1.0f;
fixDef.isSensor = false;
b2Body *topBody = self.world->CreateBody(&bodyDef);
topBody->CreateFixture(&fixDef);
}
//right
{
b2BodyDef bodyDef;
bodyDef.type = b2_staticBody;
bodyDef.position.Set((mS.width)/PTM_RATIO, (mS.height*0.5f)/PTM_RATIO);
bodyDef.linearDamping = 0.0f;
bodyDef.angularDamping = 0.0f;
bodyDef.userData = strId ;
b2PolygonShape box;
box.SetAsBox( ((bW)/PTM_RATIO), (mS.height*0.5f)/PTM_RATIO);
b2FixtureDef fixDef;
fixDef.shape = &box;
fixDef.density = 1.0f;
fixDef.friction = 0.1f;
fixDef.restitution = 1.0f;
fixDef.isSensor = false;
b2Body *topBody = self.world->CreateBody(&bodyDef);
topBody->CreateFixture(&fixDef);
}

Related

glutWarpPointer with first person camera

I'm trying to do a first person camera with GLUT, I have my get mouse speed x/y code here..
X_mouse = mousex;
Y_mouse = mousey;
current_t = static_cast<double>(glutGet(GLUT_ELAPSED_TIME));
delta_t = (current_t - previous_t)/CLOCKS_PER_SEC;
diffX = (X_mouse - Xpre);
diffY = (Y_mouse - Ypre);
if ( diffX != 0)
{
if (delta_t == 0) delta_t = 1;
Vx = diffX / delta_t;
MouseXSpd = Vx/1000.0;
}
if ( diffY != 0)
{
if (delta_t == 0) delta_t = 1;
Vx = diffY / delta_t;
MouseXSpd = Vy/1000.0;
}
glutSwapBuffers(); //<-- not sure if this is needed
previous_t = current_t;
Xpre = X_mouse;
Ypre = Y_mouse;
Then in my glutMotionFunc is just this code
void MousePosition(int x, int y) {
mousex = x;
mousey = y;
}
but having trouble with warping the mouse pointer when it gets to the edge of the window.

CorePlot refresh plot connected to table

I'm working with core plot on xCode and I want to plot some real-time incoming data via bluetooth.
I used the CPTTestAPP for Mac Os X as example and tried to adapt it to my specific case.
The first 60 points are added like it's supposed to and due the following unaltered code:
-(void)setupScatterPlots
{
static BOOL hasData = NO;
// Create one plot that uses bindings
CPTScatterPlot *boundLinePlot = [[CPTScatterPlot alloc] init];
boundLinePlot.identifier = bindingsPlot;
CPTMutableLineStyle *lineStyle = [boundLinePlot.dataLineStyle mutableCopy];
lineStyle.miterLimit = 1.0;
lineStyle.lineWidth = 2.0;
lineStyle.lineColor = [CPTColor redColor];
boundLinePlot.dataLineStyle = lineStyle;
[self.graph addPlot:boundLinePlot];
[boundLinePlot bind:CPTScatterPlotBindingXValues toObject:self withKeyPath:#"arrangedObjects.x" options:nil];
[boundLinePlot bind:CPTScatterPlotBindingYValues toObject:self withKeyPath:#"arrangedObjects.y" options:nil];
// Set plot delegate, to know when symbols have been touched
// We will display an annotation when a symbol is touched
boundLinePlot.delegate = self;
boundLinePlot.plotSymbolMarginForHitDetection = 5.0;
if ( !hasData ) {
// Add some initial data
contentArray = [NSMutableArray arrayWithCapacity:100];
for ( NSUInteger i = 0; i < 60; i++ ) {
NSNumber *x = #(1.0 + i * 0.05);
NSNumber *y = #(1.2 * arc4random() / (double)UINT32_MAX + 1.2);
[contentArray addObject:#{ #"x": x,
#"y": y }
];
}
self.content = contentArray;
hasData = YES;
}
// Auto scale the plot space to fit the plot data
// Extend the y range by 10% for neatness
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
plotSpace.allowsMomentum = YES;
[plotSpace scaleToFitPlots:#[boundLinePlot]];
CPTPlotRange *xRange = plotSpace.xRange;
CPTMutablePlotRange *yRange = [plotSpace.yRange mutableCopy];
[yRange expandRangeByFactor:CPTDecimalFromDouble(1.1)];
plotSpace.yRange = yRange;
// Restrict y range to a global range
plotSpace.globalXRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(-1.0) length:CPTDecimalFromDouble(10.0)];
plotSpace.globalYRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(-1.0) length:CPTDecimalFromDouble(5.0)];
// set the x and y shift to match the new ranges
CGFloat length = xRange.lengthDouble;
self.xShift = length - 3.0;
length = yRange.lengthDouble;
self.yShift = length - 2.0;
}
I'm using a method called insertData who looks like this:
-(void)insertData:(uint32 *) buf :(uint32 *) i
{
[contentArray addObject:#{ #"x": i,
#"y": buf }
];
NSLog(#"%#",contentArray);
self.content = contentArray;
}
where buf is my incoming data.
But when I call the insertData method, the data are appended to the array but the tab on my interface doesn't change, neither does the plot.
can anyone help me please?
thanks !
I already tried to convert the int to NSNumber by using the following :
NSNumber *ni = #(*i);
NSNumber *nbuf = #(*buf);
and:
NSNumber *ni = [NSNumber numberWithUnsignedInt:(*i);
NSNumber *nbuf = [NSNumber numberWithUnsignedInt:(*buf);
I also tried all the reload stuff I found over the internet
but none of that worked either.
#import "Controller.h"
#import "HeartRateMonitorAppDelegate.h"
static const CGFloat kZDistanceBetweenLayers = 20.0;
static NSString *const bindingsPlot = #"Bindings Plot";
static NSMutableArray *contentArray;
#interface Controller()
#property (nonatomic, readwrite, strong) IBOutlet CPTGraphHostingView *hostView;
#property (nonatomic, readwrite, strong) CPTXYGraph *graph;
#property (nonatomic, readwrite, strong) CPTPlotSpaceAnnotation *symbolTextAnnotation;
-(void)setupGraph;
-(void)setupAxes;
-(void)setupScatterPlots;
#end
#pragma mark -
#implementation Controller
#synthesize hostView;
#synthesize graph;
#synthesize symbolTextAnnotation;
+(void)initialize
{
[NSValueTransformer setValueTransformer:[CPTDecimalNumberValueTransformer new] forName:#"CPTDecimalNumberValueTransformer"];
}
-(void)awakeFromNib
{
[super awakeFromNib];
self.xShift = 0.0;
self.yShift = 0.0;
[self setupGraph];
[self setupAxes];
[self setupScatterPlots];
}
-(id)newObject:(uint32 *) buf :(uint32 *) i
{
NSLog(#"buf = %d", *buf);
NSNumber *x1 = #(*i);
NSNumber *y1 = #(*i);
return #{
#"x": x1,
#"y": y1
};
}
#pragma mark -
#pragma mark Graph Setup Methods
-(void)setupGraph
{
// Create graph and apply a dark theme
CPTXYGraph *newGraph = [[CPTXYGraph alloc] initWithFrame:NSRectToCGRect(self.hostView.bounds)];
CPTTheme *theme = [CPTTheme themeNamed:kCPTDarkGradientTheme];
[newGraph applyTheme:theme];
self.hostView.hostedGraph = newGraph;
self.graph = newGraph;
// Graph padding
newGraph.paddingLeft = 0.0;
newGraph.paddingTop = 0.0;
newGraph.paddingRight = 0.0;
newGraph.paddingBottom = 0.0;
// Plot area delegate
newGraph.plotAreaFrame.plotArea.delegate = self;
}
-(void)setupAxes
{
// Setup scatter plot space
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
plotSpace.delegate = self;
// Grid line styles
CPTMutableLineStyle *majorGridLineStyle = [CPTMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [[CPTColor colorWithGenericGray:0.2] colorWithAlphaComponent:0.75];
CPTMutableLineStyle *minorGridLineStyle = [CPTMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25;
minorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.1];
CPTMutableLineStyle *redLineStyle = [CPTMutableLineStyle lineStyle];
redLineStyle.lineWidth = 10.0;
redLineStyle.lineColor = [[CPTColor redColor] colorWithAlphaComponent:0.5];
// Axes
// Label x axis with a fixed interval policy
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)self.graph.axisSet;
CPTXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPTDecimalFromDouble(0.5);
x.orthogonalCoordinateDecimal = CPTDecimalFromDouble(0.0);
x.minorTicksPerInterval = 2;
x.majorGridLineStyle = majorGridLineStyle;
x.minorGridLineStyle = minorGridLineStyle;
NSArray *exclusionRanges = #[[CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(1.99) length:CPTDecimalFromDouble(0.02)],
[CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.99) length:CPTDecimalFromDouble(0.02)],
[CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(2.99) length:CPTDecimalFromDouble(0.02)]];
x.labelExclusionRanges = exclusionRanges;
// Label y with an automatic label policy.
CPTXYAxis *y = axisSet.yAxis;
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
y.orthogonalCoordinateDecimal = CPTDecimalFromDouble(0.0);
y.minorTicksPerInterval = 2;
y.preferredNumberOfMajorTicks = 8;
y.majorGridLineStyle = majorGridLineStyle;
y.minorGridLineStyle = minorGridLineStyle;
y.labelOffset = 10.0;
exclusionRanges = #[[CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(1.99) length:CPTDecimalFromDouble(0.02)],
[CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.99) length:CPTDecimalFromDouble(0.02)],
[CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(3.99) length:CPTDecimalFromDouble(0.02)]];
y.labelExclusionRanges = exclusionRanges;
}
-(void)setupScatterPlots
{
static BOOL hasData = NO;
// Create one plot that uses bindings
CPTScatterPlot *boundLinePlot = [[CPTScatterPlot alloc] init];
boundLinePlot.identifier = bindingsPlot;
CPTMutableLineStyle *lineStyle = [boundLinePlot.dataLineStyle mutableCopy];
lineStyle.miterLimit = 1.0;
lineStyle.lineWidth = 2.0;
lineStyle.lineColor = [CPTColor redColor];
boundLinePlot.dataLineStyle = lineStyle;
[self.graph addPlot:boundLinePlot];
[boundLinePlot bind:CPTScatterPlotBindingXValues toObject:self withKeyPath:#"arrangedObjects.x" options:nil];
[boundLinePlot bind:CPTScatterPlotBindingYValues toObject:self withKeyPath:#"arrangedObjects.y" options:nil];
// Set plot delegate, to know when symbols have been touched
// We will display an annotation when a symbol is touched
boundLinePlot.delegate = self;
boundLinePlot.plotSymbolMarginForHitDetection = 5.0;
if ( !hasData ) {
// Add some initial data
contentArray = [NSMutableArray arrayWithCapacity:100];
for ( NSUInteger i = 0; i < 5; i++ ) {
NSNumber *x = #(1.0 + i * 0.05);
NSNumber *y = #(1.2 * arc4random() / (double)UINT32_MAX + 1.2);
[contentArray addObject:#{ #"x": x,
#"y": y }
];
}
self.content = contentArray;
hasData = YES;
}
// Auto scale the plot space to fit the plot data
// Extend the y range by 10% for neatness
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)self.graph.defaultPlotSpace;
plotSpace.allowsMomentum = YES;
[plotSpace scaleToFitPlots:#[boundLinePlot]];
CPTPlotRange *xRange = plotSpace.xRange;
CPTMutablePlotRange *yRange = [plotSpace.yRange mutableCopy];
[yRange expandRangeByFactor:CPTDecimalFromDouble(1.1)];
plotSpace.yRange = yRange;
// Restrict y range to a global range
plotSpace.globalXRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(-1.0) length:CPTDecimalFromDouble(10.0)];
plotSpace.globalYRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(-1.0) length:CPTDecimalFromDouble(5.0)];
// set the x and y shift to match the new ranges
CGFloat length = xRange.lengthDouble;
self.xShift = length - 3.0;
length = yRange.lengthDouble;
self.yShift = length - 2.0;
}
-(void)insertData:(uint32 *) buf :(uint32 *) i
{
NSNumber *ni = #(*i);
//NSNumber *nbuf = #(*buf);
[contentArray addObject:#{ #"x": ni,
#"y": ni }
];
self.content = contentArray;
[graph reloadData];
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
if ( [plot isKindOfClass:[CPTBarPlot class]] ) {
return 8;
}
else {
return [self.arrangedObjects count];
}
}
-(id)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSNumber *num;
if ( [plot isKindOfClass:[CPTBarPlot class]] ) {
num = #( (index + 1) * (index + 1) );
if ( [plot.identifier isEqual:bindingsPlot] ) {
num = #(num.integerValue - 10);
}
}
else {
NSString *key = (fieldEnum == CPTScatterPlotFieldX ? #"x" : #"y");
num = (self.arrangedObjects)[index][key];
if ( fieldEnum == CPTScatterPlotFieldY ) {
num = #([num doubleValue] + 1.0);
}
}
return num;
}
-(CPTLayer *)dataLabelForPlot:(CPTPlot *)plot recordIndex:(NSUInteger)index
{
if ( [(NSString *)plot.identifier isEqualToString : bindingsPlot] ) {
return (id)[NSNull null]; // Don't show any label
}
else if ( [(NSString *)plot.identifier isEqualToString : bindingsPlot] && (index < 4) ) {
return (id)[NSNull null];
}
else if ( index % 4 ) {
return (id)[NSNull null];
}
else {
return nil; // Use default label style
}
}
#pragma mark -
#pragma mark CPTScatterPlot delegate method
-(void)scatterPlot:(CPTScatterPlot *)plot plotSymbolWasSelectedAtRecordIndex:(NSUInteger)index
{
CPTPlotSpaceAnnotation *annotation = self.symbolTextAnnotation;
if ( annotation ) {
[self.graph.plotAreaFrame.plotArea removeAnnotation:annotation];
self.symbolTextAnnotation = nil;
}
// Setup a style for the annotation
CPTMutableTextStyle *hitAnnotationTextStyle = [CPTMutableTextStyle textStyle];
hitAnnotationTextStyle.color = [CPTColor whiteColor];
hitAnnotationTextStyle.fontSize = 16.0f;
hitAnnotationTextStyle.fontName = #"Helvetica-Bold";
// Determine point of symbol in plot coordinates
NSDictionary *dataPoint = (self.arrangedObjects)[index];
NSNumber *x = dataPoint[#"x"];
NSNumber *y = dataPoint[#"y"];
NSArray *anchorPoint = #[x, y];
// Add annotation
// First make a string for the y value
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:2];
NSString *yString = [formatter stringFromNumber:y];
// Now add the annotation to the plot area
CPTTextLayer *textLayer = [[CPTTextLayer alloc] initWithText:yString style:hitAnnotationTextStyle];
annotation = [[CPTPlotSpaceAnnotation alloc] initWithPlotSpace:self.graph.defaultPlotSpace anchorPlotPoint:anchorPoint];
annotation.contentLayer = textLayer;
annotation.displacement = CGPointMake(0.0, 20.0);
[self.graph.plotAreaFrame.plotArea addAnnotation:annotation];
self.symbolTextAnnotation = annotation;
}
#pragma mark -
#pragma mark Plot area delegate method
-(void)plotAreaWasSelected:(CPTPlotArea *)plotArea
{
// Remove the annotation
CPTPlotSpaceAnnotation *annotation = self.symbolTextAnnotation;
if ( annotation ) {
[self.graph.plotAreaFrame.plotArea removeAnnotation:annotation];
self.symbolTextAnnotation = nil;
}
}
#pragma mark -
#pragma mark PDF / image export
-(IBAction)exportToPDF:(id)sender
{
NSSavePanel *pdfSavingDialog = [NSSavePanel savePanel];
[pdfSavingDialog setAllowedFileTypes:#[#"pdf"]];
if ( [pdfSavingDialog runModal] == NSOKButton ) {
NSData *dataForPDF = [self.graph dataForPDFRepresentationOfLayer];
[dataForPDF writeToURL:[pdfSavingDialog URL] atomically:NO];
}
}
-(IBAction)exportToPNG:(id)sender
{
NSSavePanel *pngSavingDialog = [NSSavePanel savePanel];
[pngSavingDialog setAllowedFileTypes:#[#"png"]];
if ( [pngSavingDialog runModal] == NSOKButton ) {
NSImage *image = [self.graph imageOfLayer];
NSData *tiffData = [image TIFFRepresentation];
NSBitmapImageRep *tiffRep = [NSBitmapImageRep imageRepWithData:tiffData];
NSData *pngData = [tiffRep representationUsingType:NSPNGFileType properties:nil];
[pngData writeToURL:[pngSavingDialog URL] atomically:NO];
}
}
#pragma mark -
#pragma mark Printing
-(IBAction)printDocument:(id)sender
{
NSPrintInfo *printInfo = [NSPrintInfo sharedPrintInfo];
NSRect printRect = NSZeroRect;
printRect.size.width = (printInfo.paperSize.width - printInfo.leftMargin - printInfo.rightMargin) * printInfo.scalingFactor;
printRect.size.height = (printInfo.paperSize.height - printInfo.topMargin - printInfo.bottomMargin) * printInfo.scalingFactor;
self.hostView.printRect = printRect;
NSPrintOperation *printOperation = [NSPrintOperation printOperationWithView:self.hostView printInfo:printInfo];
[printOperation runOperationModalForWindow:self.hostView.window
delegate:self
didRunSelector:#selector(printOperationDidRun:success:contextInfo:)
contextInfo:NULL];
}
-(void)printOperationDidRun:(NSPrintOperation *)printOperation success:(BOOL)success contextInfo:(void *)contextInfo
{
// print delegate
}
Core Plot expects the data values to be NSNumber instances, not plain integers. You can use NSDecimalNumber (a subclass of NSNumber) if you need to preserve full decimal precision.
Since you're using data bound to an NSArrayController, -reloadData and related methods will have no effect. Those are only used when providing data through a datasource. That's the only method available on iOS which is why much of the sample code and demos on the web use it.
Once an NSArrayController is initialized, you should use its methods to add or remove data rather than updating the content array directly. The CPTTestAPP demo uses -insertObject:atArrangedObjectIndex: and -removeObjectAtArrangedObjectIndex: to do this.

Scatterplot Not Showing

I'm doing an application that requires core plot for drawing charts, I'm new to this library and I am finding it pretty hard to find good documentation or examples. I'm running into a problem where the line for the graph is not being display despite the fact that the data source method is getting called and returning the right number at the right index. Also the x Axis is being displayed wrong (Check the image below(1.0)). The Y axis is set correctly and the increment is also correct. I've been playing around trying to figure out what it's wrong but I spent too much time already so I was hoping to find some one here that could help or point me at the right direction. This is my implementation file :
-(void)initPlot {
[self generateData];
[self configureHost];
[self configureGraph];
[self configurePlots];
[self configureAxes];
}
- (void)generateData{
//Array containing all the dates that will be displayed on the X axis
dates = [NSArray arrayWithObjects:#"Apr 25", #"Apr 26", #"Apr 29",#"Apr 30", #"May 1", nil];
//Dictionary containing the name of the single set and its associated color
sets = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor redColor], #"Plot 1",nil];
_dataY = [[NSMutableArray alloc] init];
[_dataY insertObject:[NSNumber numberWithFloat:618.0] atIndex:0];
[_dataY insertObject:[NSNumber numberWithFloat:613.0] atIndex:0];
[_dataY insertObject:[NSNumber numberWithFloat:613.0] atIndex:0];
[_dataY insertObject:[NSNumber numberWithFloat:614.0] atIndex:0];
[_dataY insertObject:[NSNumber numberWithFloat:604.0] atIndex:0];
_dataForPlot = [[NSMutableArray alloc] init];
for(int i = 0; i < dates.count; i++){
NSString *date = [dates objectAtIndex:i];
NSNumber *price = [_dataY objectAtIndex:i];
NSMutableDictionary *point1 = [[[NSMutableDictionary alloc] initWithObjectsAndKeys:date, #"x", price, #"y", nil] autorelease];
[_dataForPlot addObject:point1];
}
NSLog(#"Data %#",_dataForPlot);
}
-(void)configureHost {
_hostView.allowPinchScaling = NO;
}
-(void)configureGraph {
graph = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
[graph applyTheme:[CPTTheme themeNamed:kCPTPlainBlackTheme]];
_hostView.hostedGraph = graph;
graph.plotAreaFrame.masksToBorder = NO;
// Configure the Graph Padding
graph.paddingLeft = 0.0f;
graph.paddingTop = 0.0f;
graph.paddingRight = 0.0f;
graph.paddingBottom = 0.0f;
CPTMutableLineStyle *borderLineStyle = [CPTMutableLineStyle lineStyle];
borderLineStyle.lineColor = [CPTColor whiteColor];
borderLineStyle.lineWidth = 2.0f;
graph.plotAreaFrame.borderLineStyle = borderLineStyle;
graph.plotAreaFrame.paddingTop = 10.0;
graph.plotAreaFrame.paddingRight = 10.0;
graph.plotAreaFrame.paddingBottom = 40.0;
graph.plotAreaFrame.paddingLeft = 70.0;
// Set graph title
graph.title = #"Test";
// Create and set text style
CPTMutableTextStyle *titleStyle = [CPTMutableTextStyle textStyle];
titleStyle.color = [CPTColor whiteColor];
titleStyle.fontName = #"Helvetica-Bold";
titleStyle.fontSize = 16.0f;
graph.titleTextStyle = titleStyle;
graph.titlePlotAreaFrameAnchor = CPTRectAnchorTop;
graph.titleDisplacement = CGPointMake(0.0f, 10.0f);
graph.plotAreaFrame.borderLineStyle = nil;
}
- (void)configurePlots{
CPTColor *aColor = [CPTColor redColor];
CPTMutableLineStyle *barLineStyle = [[[CPTMutableLineStyle alloc] init] autorelease];
barLineStyle.lineWidth = 1.0;
barLineStyle.lineColor = [CPTColor whiteColor];
CPTMutableTextStyle *whiteTextStyle = [CPTMutableTextStyle textStyle];
whiteTextStyle.color = [CPTColor whiteColor];
// Enable user interactions for plot space
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *) graph.defaultPlotSpace;
plotSpace.allowsUserInteraction = YES;
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat(0.0) length:CPTDecimalFromFloat(5.0)];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromFloat([self lowerValue]) length:CPTDecimalFromFloat([self higherValue])];
dataSourceLinePlot = [[[CPTScatterPlot alloc] init] autorelease];
dataSourceLinePlot.identifier = #"Plot 1";
dataSourceLinePlot.dataSource = self;
[graph addPlot:dataSourceLinePlot];
CPTGradient *areaGradient = [CPTGradient gradientWithBeginningColor :[CPTColor greenColor]
endingColor :[CPTColor blackColor]];
areaGradient.angle = -90.0f ;
CPTFill *areaGradientFill = [ CPTFill fillWithGradient :areaGradient];
dataSourceLinePlot.areaFill = areaGradientFill;
dataSourceLinePlot.areaBaseValue = CPTDecimalFromString (#"0.0");
dataSourceLinePlot.interpolation = CPTScatterPlotInterpolationLinear;
// Set up plot space
[plotSpace scaleToFitPlots:[NSArray arrayWithObjects:dataSourceLinePlot, nil]];
CPTMutablePlotRange *xRange = [plotSpace.xRange mutableCopy];
[xRange expandRangeByFactor:CPTDecimalFromCGFloat(1.1f)];
plotSpace.xRange = xRange;
CPTMutablePlotRange *yRange = [plotSpace.yRange mutableCopy];
[yRange expandRangeByFactor:CPTDecimalFromCGFloat(1.4f)];
plotSpace.yRange = yRange;
// Create styles and symbols
CPTMutableLineStyle *aLineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
aLineStyle.lineWidth = 1.0;
aLineStyle.lineColor = aColor;
dataSourceLinePlot.dataLineStyle = aLineStyle;
//Add legend
CPTLegend *theLegend = [CPTLegend legendWithGraph:graph];
theLegend.numberOfRows = sets.count;
theLegend.fill = [CPTFill fillWithColor:[CPTColor colorWithGenericGray:0.15]];
theLegend.borderLineStyle = barLineStyle;
theLegend.cornerRadius = 10.0;
theLegend.swatchSize = CGSizeMake(15.0, 15.0);
whiteTextStyle.fontSize = 13.0;
theLegend.textStyle = whiteTextStyle;
theLegend.rowMargin = 5.0;
theLegend.paddingLeft = 10.0;
theLegend.paddingTop = 10.0;
theLegend.paddingRight = 10.0;
theLegend.paddingBottom = 10.0;
graph.legend = theLegend;
graph.legendAnchor = CPTRectAnchorTopLeft;
graph.legendDisplacement = CGPointMake(80.0, -10.0);
}
- (void)configureAxes{
CPTMutableTextStyle *axisTextStyle = [[CPTMutableTextStyle alloc] init];
axisTextStyle.color = [CPTColor whiteColor];
axisTextStyle.fontName = #"Helvetica-Bold";
axisTextStyle.fontSize = 11.0f;
// Grid line styles
CPTMutableLineStyle *majorGridLineStyle = [CPTMutableLineStyle lineStyle];
majorGridLineStyle.lineWidth = 0.75;
majorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.1];
CPTMutableLineStyle *minorGridLineStyle = [CPTMutableLineStyle lineStyle];
minorGridLineStyle.lineWidth = 0.25;
minorGridLineStyle.lineColor = [[CPTColor whiteColor] colorWithAlphaComponent:0.1];
// Line Style
CPTMutableLineStyle *lineStyle = [CPTMutableLineStyle lineStyle];
lineStyle.lineColor = [CPTColor whiteColor];
lineStyle.lineWidth = 2.0f;
CPTMutableLineStyle *axisLineStyle = [CPTMutableLineStyle lineStyle];
axisLineStyle.lineWidth = 2.0f;
axisLineStyle.lineColor = [CPTColor whiteColor];
//Axises
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
//Y axis
CPTXYAxis *y = axisSet.yAxis;
y.title = #"Price";
y.titleOffset = 50.0f;
y.labelingPolicy = CPTAxisLabelingPolicyAutomatic;
y.majorGridLineStyle = majorGridLineStyle;
y.minorGridLineStyle = minorGridLineStyle;
y.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0];
y. majorIntervalLength = CPTDecimalFromString(#"5");
y.minorTicksPerInterval = 4;
y.orthogonalCoordinateDecimal = CPTDecimalFromString(#"0");
y.minorTickLineStyle = nil;
y.labelOffset = 2.0f;
// Configure x-axis
CPTXYAxis *x = axisSet.xAxis;
x. majorIntervalLength = CPTDecimalFromString (#"5");
x.orthogonalCoordinateDecimal = CPTDecimalFromInt(0);
x.majorIntervalLength = CPTDecimalFromInt(5);
x.minorTicksPerInterval = 0;
x.labelingPolicy = CPTAxisLabelingPolicyNone;
x.majorGridLineStyle = majorGridLineStyle;
x.axisConstraints = [CPTConstraints constraintWithLowerOffset:0.0];
NSMutableArray *customLabels = [NSMutableArray arrayWithCapacity:[_dataForPlot count]];
static CPTMutableTextStyle *labelTextStyle = nil;
labelTextStyle = [[CPTMutableTextStyle alloc] init];
labelTextStyle.color = [CPTColor whiteColor];
labelTextStyle.fontSize = 10.0f;
int index = 0;
for(NSString *date in dates){
CPTAxisLabel *newLabel = [[CPTAxisLabel alloc] initWithText:date textStyle:labelTextStyle];
newLabel.tickLocation = CPTDecimalFromInt(index);
newLabel.offset = x.labelOffset + x.majorTickLength + 5;
newLabel.rotation = M_PI / 4;
[customLabels addObject:newLabel];
[newLabel release];
index++;
}
x.axisLabels = [NSSet setWithArray:customLabels];
}
- (float)higherValue{
NSNumber* max = [_dataY valueForKeyPath:#"#max.self"];
return [max floatValue];
}
- (float)lowerValue{
NSNumber* min = [_dataY valueForKeyPath:#"#min.self"];
return [min floatValue];
}
The Data Source Methods :
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot {
return dates.count;
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index {
NSString *key = (fieldEnum == CPTScatterPlotFieldX ? #"x" : #"y");
NSNumber *num = 0;
//if ( [(NSString *)plot.identifier isEqualToString:#"Plot 1"] ) {
num = [[_dataForPlot objectAtIndex:index] valueForKey:key];
if ( fieldEnum == CPTScatterPlotFieldX ) {
num = 0;
}
//}
CABasicAnimation *fadeInAnimation = [CABasicAnimation animationWithKeyPath:#"opacity"];
fadeInAnimation.duration = 1.0f;
fadeInAnimation.removedOnCompletion = NO;
fadeInAnimation.fillMode = kCAFillModeForwards;
fadeInAnimation.toValue = [NSNumber numberWithFloat:2.0];
[dataSourceLinePlot addAnimation:fadeInAnimation forKey:#"animateOpacity"];
NSLog(#"NUM : %# for key : %# at index : %i",num,key,index);
return num;
}
This is the image :
The x-axis is displayed exactly as you told it. It ranges between -0.25 and 5.25 (0 to 5 expanded by 10%) with five labels at 0, 1, 2, 3, and 4.
The datasource returns nil (0) for the CPTScatterPlotFieldX field for every point. This tells the plot to ignore that point. Based on the plot place range you've set up, you should return an NSNumber containing the index for that field.

Program built using Unity3D Freezing PC - Sporadic

My program that I built using Unity3D sporadically freezes, and this action freezes my computer. I'm unable to pinpoint the root cause. I had placed logs all over my project, but the game failed to freeze.
Has any Unity3D developer experience their apps sporadically freeze in the manner in which I am describing? Does anyone have any ideas or suggestions?
Due to a 30K character limit, the below object has been modified slightly. This is the object I believe contains a flaw, but I am unable to identify this flaw.
public class gamePlayController : MonoBehaviour {
void Start () {
int i = 0;
int selectedPlayers = PlayerPrefs.GetInt("TotalPlayers");
foreach( GameObject touchable in GameObject.FindGameObjectsWithTag("Touchable") )
{
touchable.SetActive(false);
touchable.AddComponent(typeof(PlayerCollisionDispatcher));
PlayerCollisionDispatcher nextDispatcher = touchable.GetComponent<PlayerCollisionDispatcher>();
nextDispatcher.currentGameObject = touchable;
nextDispatcher.gameObject.AddComponent("AudioSource");
for(i = 0; i < this.m_Players.Count; i++)
{
if(string.Compare(touchable.name, this.m_Players[i].name) < 0)
{
break;
}
}
if(i < this.m_Players.Count)
{
this.m_Players.Insert(i, touchable);
}
else
{
this.m_Players.Add(touchable);
}
}
while(this.m_Players.Count > selectedPlayers)
{
this.m_Players.RemoveRange(selectedPlayers, this.m_Players.Count - selectedPlayers);
}
this.restartGame();
}
void OnGameTimer(object sender, ElapsedEventArgs e)
{
}
void Update() {
Vector3 vector = m_ArialCamera.camera.transform.position;
vector.x = Mathf.Abs((1500 * this.m_ArialView.x) - 1500) + 250;
vector.y = (600 * this.m_ArialView.y) + 100;
vector.z = (1500 * this.m_ArialView.z) + 250;
m_ArialCamera.camera.transform.position = vector;
if(this.m_IsGameOver)
{
Application.LoadLevel("Replay Screen");
}
else if(this.m_SimulateCamera)
{
this.SimulateCamera();
}
else if(m_AutoPluck)
{
this.AutoPluck();
}
else if(Time.timeScale != 0.0f && this.m_Dispatcher && this.m_Dispatcher.didObjectStop)
{
this.determineTurnOutcome();
}
else if(Time.timeScale != 0.0f && this.m_Dispatcher && this.m_Dispatcher.didObjectMove)
{
this.m_Dispatcher.trackMovementProgress();
}
else if(Time.timeScale != 0.0f && this.m_Dispatcher
&& this.m_Players[this.m_PlayerIndex].rigidbody.velocity.magnitude > 15.0f
&& this.m_Dispatcher.didPluck)
{
this.m_Dispatcher.didObjectMove = true;
}
}
void restartGame()
{
this.m_PlayerIndex = -1;
foreach( GameObject touchable in this.m_Players)
{
GameObject startField = GameObject.FindWithTag ("StartField");
touchable.SetActive(false);
touchable.rigidbody.useGravity = false;
touchable.rigidbody.velocity = Vector3.zero;
touchable.rigidbody.AddForce(Vector3.zero);
touchable.rigidbody.AddTorque(Vector3.zero);
if(startField)
{
Vector3 nextPoint = startField.renderer.bounds.center;
nextPoint.y = 11.0f;
touchable.transform.position = nextPoint;
}
touchable.rigidbody.useGravity = true;
}
this.startNextPlayer();
}
void startNextPlayer()
{
bool isActivePlayerReady = true;
do{
if(this.m_PlayerIndex != -1)
{
audioPlayer.PlayAudio("Audio/Next Player");
}
this.m_PlayerIndex = (this.m_PlayerIndex + 1)%this.m_Players.Count;
this.m_Dispatcher = this.m_Players[this.m_PlayerIndex].GetComponent<PlayerCollisionDispatcher>();
if(this.m_Dispatcher && !this.m_Dispatcher.isGameOver && !this.m_Dispatcher.didEnterMud)
{
if(!this.m_Players[this.m_PlayerIndex].activeSelf)
{
this.m_Dispatcher.startGame();
this.m_Players[this.m_PlayerIndex].SetActive(true);
}
this.m_Dispatcher.startTurn();
}
}
while(!isActivePlayerReady);
Vector3 vector = this.m_Players[this.m_PlayerIndex].transform.position;
vector.x = (1500 * this.m_ArialView.x) + 250;
vector.y = 300;
vector.z = (1500 * this.m_ArialView.z) + 250;
m_ArialCamera.camera.transform.position = vector;
this.setAnnouncement("Player " + this.m_Players[this.m_PlayerIndex].name + "'s Turn");
if(this.m_PlayerIndex != 0)
{
this.m_IsSimulating = PlayerPrefs.GetInt("SimulatePlayer" + this.m_Players[this.m_PlayerIndex].name);
this.m_IsSimulating = 1;
}
else
{
this.m_IsSimulating = 0;
}
GameObject mainCamera = GameObject.FindWithTag ("MainCamera");
MouseOrbit mo = null;
if(mainCamera)
{
mo = mainCamera.GetComponent<MouseOrbit>();
}
if(this.m_IsSimulating >= 1)
{
this.StartSimulation();
if(mo)
{
mo.DoFreeze = true;
}
}
else
{
if(mo)
{
mo.DoFreeze = false;
}
}
}
void StartSimulation()
{
System.Random random = new System.Random();
StringBuilder sb = new StringBuilder();
int randomNumber = 0;
//determine either the player object or the next block
if(this.m_Dispatcher.isKiller)
{
m_SimulateToObject = this.m_Players[randomNumber%this.m_Players.Count];
randomNumber = random.Next(0, 100);
}
else
{
sb.AppendFormat("{0:D2}", this.m_Dispatcher.targetScore);
Debug.Log("target score=" + sb.ToString());
foreach(GameObject scoreField in GameObject.FindGameObjectsWithTag("ScoreField"))
{
if(scoreField.name == sb.ToString())
{
m_SimulateToObject = scoreField;
break;
}
}
}
this.m_IsTargetInitiallyVisible = false;
this.m_SimulationTimer = new System.Timers.Timer();
this.m_SimulationTimer.Elapsed+=new ElapsedEventHandler(TriggerCameraSimulation);
this.m_SimulationTimer.Interval=2500;
this.m_SimulationTimer.Enabled=true;
}
void TriggerCameraSimulation(object sender, ElapsedEventArgs e)
{
this.m_SimulationTimer.Enabled = false;
this.m_SimulationTimer.Dispose();
this.m_SimulateCamera = true;
}
void SimulateCamera()
{
GameObject mainCamera = GameObject.FindWithTag ("MainCamera");
MouseOrbit mo = null;
this.m_SimulationTimer.Enabled = false;
this.m_SimulationTimer.Dispose();
if(mainCamera)
{
mo = mainCamera.GetComponent<MouseOrbit>();
if(!this.m_IsTargetInitiallyVisible)
{
mo.IsManualMove = true;
mainCamera.transform.position = this.m_Players[this.m_PlayerIndex].transform.position;
mainCamera.transform.LookAt(this.m_SimulateToObject.transform, Vector3.up);
this.m_IsTargetInitiallyVisible = true;
}
else if(this.m_SimulateCamera)
{
if(mo.getDistance() >= 10.0f)
{
this.m_SimulateCamera = false;
}
mo.setDistance(-0.001f);
}
}
if(!this.m_SimulateCamera)
{
this.m_SimulationTimer = new System.Timers.Timer();
this.m_SimulationTimer.Elapsed+=new ElapsedEventHandler(TriggerSimulatedPluck);
this.m_SimulationTimer.Interval=2000;
this.m_SimulationTimer.Enabled=true;
}
}
void TriggerSimulatedPluck(object sender, ElapsedEventArgs e)
{
this.m_SimulationTimer.Enabled = false;
this.m_SimulationTimer.Dispose();
this.m_AutoPluck = true;
}
void AutoPluck()
{
System.Random random = new System.Random();
GameObject mainCamera = GameObject.FindWithTag ("MainCamera");
MouseOrbit mo = null;
float applyForce = 0.0f;
float slope = 0.00028648399272739457f;
float y_int = 0.2908366193449838f;
Vector3 vTorque = Vector3.zero;
int simulateId = PlayerPrefs.GetInt("SimulatePlayer" + this.m_Players[this.m_PlayerIndex].name);
int seed = (5 * ((int)(SimulationOptions.Pro) - simulateId));
int xSeed = 0;
int ySeed = 0;
int zSeed = 0;
int sign = random.Next(1, 1000)%2;
int range = random.Next(1, 1000)%seed;
int myValue = 0;
this.m_SimulationTimer.Enabled = false;
this.m_SimulationTimer.Dispose();
if(mainCamera)
{
mo = mainCamera.GetComponent<MouseOrbit>();
mo.IsManualMove = false;
}
this.m_AutoPluck = false;
if(simulateId >= 1)
{
float distance = Vector3.Distance(this.m_Players[this.m_PlayerIndex].transform.position,
this.m_SimulateToObject.transform.position);
if(simulateId != (int)(SimulationOptions.Pro))
{
myValue = random.Next(1, 6);
seed = (int)(myValue * ((int)(SimulationOptions.Pro) - simulateId));
sign = random.Next(1, 2);
range = random.Next(1, seed);
if(random.Next(1, 1000)%3 == 0)
{
distance += (sign == 1 ? range : -range);
}
}
vTorque.x = (float)(random.Next(1, 90));
vTorque.y = (float)(random.Next(1, 90));
vTorque.z = (float)(random.Next(1, 90));
applyForce = (slope * distance) + y_int;
this.m_Dispatcher.pluckObject(applyForce, vTorque);
}
}
void determineTurnOutcome()
{
int number = -1;
bool canActivePlayerContinue = false;
bool isAutoReward = false;
bool didElinimatePlayer = false;
foreach(GameObject nextObject in this.m_Players)
{
PlayerCollisionDispatcher nextDispatcher = nextObject.GetComponent<PlayerCollisionDispatcher>();
if(nextObject.activeSelf && !nextDispatcher.isGameOver && !nextDispatcher.isActive)
{
if(nextDispatcher.currentScore == nextDispatcher.targetScore)
{
nextDispatcher.totalScore = nextDispatcher.targetScore;
int.TryParse(nextDispatcher.name, out number);
nextDispatcher.targetScore++;
if(nextDispatcher.totalScore >= 13 || nextDispatcher.targetScore > 13)
{
nextDispatcher.totalScore = 13;
nextDispatcher.targetScore = 13;
nextDispatcher.isKiller = true;
this.setMaterial(nextDispatcher.renderer, "killers", nextDispatcher.name);
}
else
{
this.setMaterial(nextDispatcher.renderer, "numbers", nextDispatcher.name);
}
}
else if(nextDispatcher.didKillerCollide && (nextDispatcher.didLeaveBoard || nextDispatcher.didLeaveBounds))
{
this.setMaterial(nextDispatcher.renderer, "eliminated", nextDispatcher.name);
nextDispatcher.isGameOver = true;
didElinimatePlayer = true;
}
else if(nextDispatcher.didPlayerCollide && (nextDispatcher.didLeaveBoard || nextDispatcher.didLeaveBounds))
{
if(int.TryParse(nextDispatcher.name, out number))
{
nextDispatcher.targetScore = 1;
nextDispatcher.totalScore = 0;
}
}
else if(nextDispatcher.didEnterMud)
{
this.setMaterial(nextDispatcher.renderer, "mudd", nextDispatcher.name);
nextDispatcher.isKiller = false;
}
else if(nextDispatcher.isInMud && !nextDispatcher.didEnterMud)
{
isAutoReward = true;
}
else
{
this.setMaterial(nextDispatcher.renderer, "numbers", nextDispatcher.name);
}
}
nextDispatcher.transferStates();
}
if(this.m_Dispatcher.isKiller && !didElinimatePlayer)
{
this.setMaterial(this.m_Dispatcher.renderer, "numbers", this.m_Dispatcher.name);
this.m_Dispatcher.totalScore = 0;
this.m_Dispatcher.targetScore = 1;
this.m_Dispatcher.isKiller = false;
}
else if(this.m_Dispatcher.didEnterMud)
{
this.setMaterial(this.m_Dispatcher.renderer, "mud", this.m_Dispatcher.name);
}
else if(this.m_Dispatcher.currentScore == this.m_Dispatcher.targetScore || isAutoReward)
{
this.m_Dispatcher.totalScore = this.m_Dispatcher.targetScore;
canActivePlayerContinue = true;
this.m_Dispatcher.consecutivePops++;
int.TryParse(this.m_Dispatcher.name, out number);
this.m_Dispatcher.targetScore++;
this.setMaterial(this.m_Dispatcher.renderer, "numbers", this.m_Dispatcher.name);
}
else
{
this.setMaterial(this.m_Dispatcher.renderer, "numbers", this.m_Dispatcher.name);
}
this.isWinnerAnnounced();
if(!this.m_IsGameOver && !canActivePlayerContinue)
{
this.m_Dispatcher.endTurn();
this.startNextPlayer();
}
else if(canActivePlayerContinue)
{
this.m_Dispatcher.transferStates();
this.m_Dispatcher.isActive = true;
this.m_Dispatcher.didObjectMove = false;
this.m_Dispatcher.didObjectStop = false;
if(this.m_IsSimulating >= 1)
{
this.StartSimulation();
}
}
this.m_ForceValue = 0.0f;
}
void isWinnerAnnounced()
{
StringBuilder sb = new StringBuilder();
int totalPlayers = 0;
string winner = string.Empty;
int number = -1;
int totalPlayersInMud = 0;
foreach(GameObject nextObject in this.m_Players)
{
PlayerCollisionDispatcher nextDispatcher = nextObject.GetComponent<PlayerCollisionDispatcher>();
if(!nextDispatcher.isGameOver)
{
totalPlayers++;
winner = nextObject.name;
}
if(nextDispatcher.isInMud)
{
totalPlayersInMud++;
}
}
if(totalPlayers == 1)
{
if(winner != string.Empty && int.TryParse(winner, out number))
{
sb.AppendFormat("Congratulations Player {0}", number);
PlayerPrefs.SetString("WinningPlayer", sb.ToString());
}
else
{
PlayerPrefs.SetString("WinningPlayer", "Congratulations");
}
this.m_IsGameOver = true;
}
else if(totalPlayersInMud == this.m_Players.Count)
{
PlayerPrefs.SetString("WinningPlayer", "All players are stuck in the mud!");
this.m_IsGameOver = true;
}
}
void setMaterial(Renderer renderer, string state, string playerId)
{
StringBuilder sbNextImage = new StringBuilder();
sbNextImage.AppendFormat("Materials/playerObjects/{0}/{1}", state, playerId);
Material newMat = Resources.Load(sbNextImage.ToString(), typeof(Material)) as Material;
if(newMat)
{
renderer.material = newMat;
}
else
{
Debug.Log("FAILED to set material: " + sbNextImage.ToString());
}
}
void setAnnouncement(string text)
{
this.m_IsAnnouncement = true;
this.m_AnnouncementHeight = (int)(Screen.height * 0.5);
this.m_AnnouncementText = text;
}
void OnGUI() {
GUIStyle labelStyle = GUI.skin.label;
int number = -1;
StringBuilder scoreDetails = new StringBuilder();
StringBuilder turnDetails = new StringBuilder();
float x = 0;
float y = 0;
float w = 64.0f;
float h = 32.0f;
float alpha = 1.0f;
if(this.m_IsAnnouncement)
{
this.displayAnnouncement();
}
labelStyle.normal.textColor = new Color(1.0f, 1.0f, 1.0f, alpha);
Texture2D texture = new Texture2D(32, 32, TextureFormat.ARGB32, false);
for(int i = 0; i < 32; i++)
{
for(int j = 0; j < 32; j++)
{
texture.SetPixel(i, j, new Color(0.0f, 0.0f, 0.0f, 0.25f));
}
}
texture.Apply();
labelStyle.normal.background = texture;
if(this.m_DoShowScore)
{
foreach(GameObject nextObject in this.m_Players)
{
PlayerCollisionDispatcher nextDispatcher = nextObject.GetComponent<PlayerCollisionDispatcher>();
int.TryParse(nextDispatcher.name, out number);
if(nextDispatcher.isGameOver)
{
scoreDetails.AppendFormat("\tPlayer {0}: Game Over\n", number);
}
else if(nextDispatcher.didEnterMud)
{
scoreDetails.AppendFormat("\tPlayer {0}: In The Mudd\n", number);
}
else if(nextDispatcher.isKiller)
{
scoreDetails.AppendFormat("\tPlayer {0}: Killer\n", number);
}
else
{
scoreDetails.AppendFormat("\tPlayer {0}: {1}\n", number, nextDispatcher.totalScore);
}
}
GUI.Label (new Rect (0, 0, 225, 100), scoreDetails.ToString());
}
w = 64.0f;
h = 32.0f;
x = Screen.width - w;
y = Screen.height - h;
if(GUI.Button (new Rect (x, y, w, h), "Menu"))
{
audioPlayer.PlayAudio("Audio/Click");
this.m_IsMenuShowing = !this.m_IsMenuShowing;
}
if(this.m_IsMenuShowing)
{
w = (64.0f * this.m_MenuText.Length);
h = 32.0f;
x = Screen.width - w - 64.0f;
y = Screen.height - h;
int selOption = GUI.Toolbar(new Rect(x, y, w, h), this.m_MenuOption, this.m_MenuText);
if(selOption != this.m_MenuOption)
{
audioPlayer.PlayAudio("Audio/Click");
this.m_MenuOption = -1;
this.m_IsMenuShowing = !this.m_IsMenuShowing;
switch(selOption)
{
case (int)(MenuOptions.ArialViewOption): //arial
this.m_ArialCamera.SetActive(!this.m_ArialCamera.activeSelf);
break;
case (int)(MenuOptions.VolumeOption): //mute
int muteVolume = PlayerPrefs.GetInt("MuteVolume");
muteVolume = (muteVolume + 1)%2;
PlayerPrefs.SetInt("MuteVolume", muteVolume);
if(muteVolume == 0)
{
this.m_MenuText[(int)(MenuOptions.VolumeOption)] = "Mute";
}
else
{
this.m_MenuText[(int)(MenuOptions.VolumeOption)] = "Volume";
}
break;
case (int)(MenuOptions.PauseOption): //pause
if(Time.timeScale == 0.0f)
{
this.setAnnouncement("Continuing Game Play");
Time.timeScale = this.m_Speed;
this.m_MenuText[(int)(MenuOptions.PauseOption)] = "Pause";
}
else
{
this.setAnnouncement("Game Is Paused");
Time.timeScale = 0.0f;
this.m_MenuText[(int)(MenuOptions.PauseOption)] = "Play";
}
break;
case (int)(MenuOptions.ScoresOption): //scores
this.m_DoShowScore = !this.m_DoShowScore;
break;
case (int)(MenuOptions.RestartOption): //restart
Time.timeScale = this.m_Speed;
this.restartGame();
break;
case (int)(MenuOptions.QuitOption): //quit
Application.LoadLevel("Opening Screen");
break;
default:
break;
}
}
}
if(this.m_ArialCamera.activeSelf)
{
x = Screen.width * 0.7f - 10.0f;
y = 0;
w = 10.0f;
h = Screen.height * 0.3f;
this.m_ArialView.z = GUI.VerticalSlider (new Rect(x, y, w, h), this.m_ArialView.z, 1.0f, 0.0f);
x = Screen.width * 0.7f;
y = Screen.height * 0.3f;
w = Screen.width * 0.3f;
h = 10.0f;
this.m_ArialView.x = GUI.HorizontalSlider (new Rect(x, y, w, h), this.m_ArialView.x, 1.0f, 0.0f);
x = Screen.width * 0.7f;
y = Screen.height * 0.3f + 12.0f;
w = Screen.width * 0.3f;
h = 10.0f;
this.m_ArialView.y = GUI.HorizontalSlider (new Rect(x, y, w, h), this.m_ArialView.y, 1.0f, 0.0f);
}
int.TryParse(this.m_Players[this.m_PlayerIndex].name, out number);
turnDetails.AppendFormat("\tPlayer {0}'s Turn\n", number);
turnDetails.AppendFormat("\tNext Goal: {0}\n", this.m_Dispatcher.targetScore);
GUI.Label (new Rect (0, Screen.height - 100, 225, 100), turnDetails.ToString());
if(!this.m_Dispatcher.didObjectMove && m_IsSimulating == 0)
{
x = 250.0f;
y = Screen.height - 190.0f;
w = 30.0f;
h = 150.0f;
this.m_ForceValue = GUI.VerticalSlider (new Rect(x, y, w, h), m_ForceValue, 1.0f, 0.0f);
x = 250.0f;
y = Screen.height - 30.0f;
w = 100.0f;
h = 30.0f;
if(GUI.Button (new Rect(x, y, w, h), "Pluck!"))
{
System.Random random = new System.Random();
Vector3 vTorque = Vector3.zero;
int xSeed = 0;
int ySeed = 0;
int zSeed = 0;
xSeed = (random.Next(1, 45));
ySeed = (random.Next(1, 45));
zSeed = (random.Next(1, 45));
vTorque = new Vector3(xSeed, ySeed, zSeed);
this.m_Dispatcher.pluckObject(this.m_ForceValue, vTorque);
}
}
}
void displayAnnouncement()
{
float x = 0;
float y = 0;
float w = 0;
float h = 0;
float alpha = 1.0f;
GUIStyle announcementStyle = null;
GUIStyle labelStyle = null;
announcementStyle = new GUIStyle();
labelStyle = GUI.skin.label;
labelStyle.normal.textColor = new Color(1.0f, 1.0f, 1.0f, alpha);
x = (int)(Screen.width * 0.25);
y = (int)m_AnnouncementHeight;
w = (int)(Screen.width * 0.5);
h = 100;
alpha = (float)m_AnnouncementHeight/(float)(Screen.height * 0.5);
announcementStyle.fontSize = 32;
announcementStyle.alignment = TextAnchor.MiddleCenter;
announcementStyle.fontStyle = FontStyle.BoldAndItalic;
announcementStyle.normal.textColor = new Color(1.0f, 1.0f, 1.0f, alpha);
GUI.Label (new Rect (x, y, w, h), this.m_AnnouncementText, announcementStyle);
if(Time.timeScale != 0.0f)
{
if((this.m_AnnouncementHeight + h) <= 0)
{
this.m_IsAnnouncement = false;
this.m_AnnouncementHeight = (int)(Screen.height * 0.5);
}
else
{
this.m_AnnouncementHeight -= 1;
}
}
}
}
-----------
I believe I have narrowed the freezing down. Simulated testing results is leading me to believe that my problem is inside the OnGUI() method. I have commented that method out all together, and my app is operating smoothly. I'll figure this out, unless someone beats me to the root cause and solution.
I solved it...
My initial suspicions were correct: the problem did lie within the OnGUI() method. I moved the following source code to the Start() method. It made sense, since I'm only building a transparent background texture once.:
Texture2D texture = new Texture2D(32, 32, TextureFormat.ARGB32, false);
for(int i = 0; i < 32; i++)
{
for(int j = 0; j < 32; j++)
{
texture.SetPixel(i, j, new Color(0.0f, 0.0f, 0.0f, 0.25f));
}
}
texture.Apply();

Box2d elastic rope joint

I'm writing a game, and I need to make up a rope. I maked it by b2RopeJoint, but there I have not found an opportunity to make it elastic.
Then I looked for b2DistanceJoint, everything is cool with the elasticity, but I can't find an ability to set a limit only to the maximum distance (without minimum one).
How can I do it?
Try this.
-(void) CreateElasticRope {
//=======Params
// Position and size
b2Vec2 lastPos = b2Vec2(4,4); //set position first body
float widthBody = 0.35;
float heightBody = 0.1;
// Body params
float density = 0.05;
float restitution = 0.5;
float friction = 0.5;
// Distance joint
float dampingRatio = 0.0;
float frequencyHz = 0;
// Rope joint
float kMaxWidth = 1.1;
// Bodies
int countBodyInChain = 15;
b2Body* prevBody;
//========Create bodies and joints
for (int k = 0; k < countBodyInChain; k++) {
b2BodyDef bodyDef;
if(k==0 ) bodyDef.type = b2_staticBody; //first body is static
else bodyDef.type = b2_dynamicBody;
bodyDef.position = lastPos;
lastPos += b2Vec2(2*widthBody, 0); //modify b2Vect for next body
bodyDef.fixedRotation = YES;
b2Body* body = world->CreateBody(&bodyDef);
b2PolygonShape distBodyBox;
distBodyBox.SetAsBox(widthBody, heightBody);
b2FixtureDef fixDef;
fixDef.density = density;
fixDef.restitution = restitution;
fixDef.friction = friction;
fixDef.shape = &distBodyBox;
body->CreateFixture(&fixDef);
body->SetHealth(9999999);
body->SetLinearDamping(0.0005f);
if(k>0) {
//Create distance joint
b2DistanceJointDef distJDef;
b2Vec2 anchor1 = prevBody->GetWorldCenter();
b2Vec2 anchor2 = body->GetWorldCenter();
distJDef.Initialize(prevBody, body, anchor1, anchor2);
distJDef.collideConnected = false;
distJDef.dampingRatio = dampingRatio;
distJDef.frequencyHz = frequencyHz;
world->CreateJoint(&distJDef);
//Create rope joint
b2RopeJointDef rDef;
rDef.maxLength = (body->GetPosition() - prevBody->GetPosition()).Length() * kMaxWidth;
rDef.localAnchorA = rDef.localAnchorB = b2Vec2_zero;
rDef.bodyA = prevBody;
rDef.bodyB = body;
world->CreateJoint(&rDef);
} //if k>0
prevBody = body;
} //for
}
There's a 2.2 style ropejoint implementation here: https://github.com/aaronfarr/box2Dweb
You can use both a rope joint and a distance joint together. Make the distance of the rope joint a bit longer than the distance joint.
From the Box2D testbed example, I modified the "Web" example as follows:
#ifndef ELASTICROPE_H
#define ELASTICROPE_H
#define NUM_JOINTS 7
#define NUM_LINKS 8
class ElasticRope : public Test
{
public:
ElasticRope()
{
b2Body* ground = NULL;
{
b2BodyDef bd;
ground = m_world->CreateBody(&bd);
b2EdgeShape shape;
shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f));
ground->CreateFixture(&shape, 0.0f);
}
{
b2CircleShape shape;
shape.m_radius = 0.8f;
// create bodies
for (int b = 0; b < NUM_LINKS; b++) {
b2BodyDef bd;
bd.type = b2_dynamicBody;
bd.position.Set(5.0f, NUM_LINKS-b);
m_bodies[b] = m_world->CreateBody(&bd);
m_bodies[b]->CreateFixture(&shape, 5.0f);
}
for (int j = 0; j < NUM_JOINTS; j++) {
b2DistanceJointDef jd;
b2Vec2 p1, p2, d;
jd.frequencyHz = 5.0f;
jd.dampingRatio = 1.0f;
jd.bodyA = m_bodies[j];
jd.bodyB = m_bodies[j+1];
m_joints[j] = m_world->CreateJoint(&jd);
}
}
}
void Step(Settings* settings)
{
Test::Step(settings);
m_debugDraw.DrawString(5, m_textLine, "This demonstrates an elastic rope.");
m_textLine += DRAW_STRING_NEW_LINE;
}
void JointDestroyed(b2Joint* joint)
{
for (int32 i = 0; i < 8; ++i)
{
if (m_joints[i] == joint)
{
m_joints[i] = NULL;
break;
}
}
}
static Test* Create()
{
return new ElasticRope;
}
b2Body* m_bodies[NUM_LINKS];
b2Joint* m_joints[NUM_JOINTS];
};
#endif // ELASTICROPE_H
Its far from perfect, but may be a starting point.

Resources