C# OutOfRangeException that should be impossible - c#

I am so confessed right now I don't even know how to properly form this question.
I have some code (as shown below) that is run on a different thread with the variable i not being referenced anywhere else that could interfere with it here. I just don't understand what is happening to cause this error, I put some watchers down with visual studio code and the values all seem to be fine and in range but almost randomly out of nowhere I will get this error.
Is it possible that this is caused by another section of code despite to my best knowledge being completely isolated from it? I even went as far to rename all other uses of i to different letters and I still get this problem.
Is it just something with for loops?
Am I somehow modifying i without even know it?
I just don't even know what to ask.
Here is the full code
`
using SFML.Graphics;
using SFML.Window;
using System.Diagnostics;
using System.Numerics;
namespace RenderEngine
{
public class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
PhysicsEngine re = new PhysicsEngine();
for (int i = 0; i < 100; i++)
{
Debug.WriteLine(i);
}
}
}
public class PhysicsEngine
{
Solver solver = new Solver();
public void RenderEngine2()
{
ContextSettings settings = new ContextSettings();
settings.AntialiasingLevel = 8;
RenderWindow window = new RenderWindow(new VideoMode(2000, 1000), "Poop", Styles.Default, settings);
SFML.Graphics.Color color = new SFML.Graphics.Color(0, 0, 0, 0);
window.SetVerticalSyncEnabled(true);
CircleShape shape = new CircleShape(5);
shape.FillColor = new SFML.Graphics.Color(0, 0, 255, 255);
window.Closed += handelclose;
int drawcount = 0;
while (window.IsOpen)
{
window.Clear(color);
window.DispatchEvents();
try
{
foreach (Partical partical in solver.Particals)
{
shape.Position = new SFML.System.Vector2f((partical.position.X), (partical.position.Y));
window.Draw(shape);
drawcount++;
}
drawcount = 0;
}
catch
{
Debug.WriteLine("notready yet");
}
window.Display();
}
void handelclose(object sender, EventArgs e)
{
window.Close();
Environment.Exit(Environment.ExitCode);
}
}
List<Partical> todraw = new List<Partical>();
void EngineLoop()
{
while (true)
{
foreach (Partical partical in solver.Particals)
{
int x = (int)Math.Round(partical.position.X/10);
int y = (int)Math.Round(partical.position.Y/10);
List<int> ts = solver.Grid[x, y];
if (ts != null)
{
for (int brokenint = 0; brokenint < ts.Count; brokenint++)
{
Debug.WriteLine(partical.ID);
Debug.WriteLine(ts[brokenint]);
if (partical.ID != ts[brokenint])
{
Vector2 pos = new Vector2(partical.ID, ts[brokenint]);
if (solver.Collision.Count > 0)
{
if (!solver.Collision.Contains(pos))
solver.Collision.Add(pos);
}
else
{
solver.Collision.Add(pos);
}
}
}
}
}
}
}
private int particalcount = 10;
bool canstart = false;
public PhysicsEngine()
{
Parallel.Invoke(() =>
{
while (!canstart) { Thread.Sleep(100); }
Debug.WriteLine("third thread");
RenderEngine2();
},
() =>
{
while (!canstart) { Thread.Sleep(100); }
Debug.WriteLine("engine started");
EngineLoop();
},
() =>
{
Debug.WriteLine("first thread");
PhysicsLoop(this);
}
);
}
void PhysicsLoop(PhysicsEngine PhyEng)
{
int frames = 0;
long second = 0;
PhysicsStart(PhyEng);
Thread.Sleep(1000);
Stopwatch sw = Stopwatch.StartNew();
solver.startupdate();
while (true)
{
sw.Start();
todraw = solver.Particals;
solver.update();
frames++;
if (second != (Stopwatch.GetTimestamp() / Stopwatch.Frequency))
{
second = (Stopwatch.GetTimestamp() / Stopwatch.Frequency);
Debug.WriteLine(frames);
frames = 0;
}
sw.Stop();
sw.Reset();
if (sw.ElapsedMilliseconds < 15)
Thread.Sleep(15 - (int)sw.ElapsedMilliseconds);
}
}
void PhysicsStart(PhysicsEngine phyeng)
{
for (int i = 0; i < 210; i++)
{
for (int j = 0; j < 110; j++)
{
solver.Grid[i,j] = new List<int>();
}
}
Random rand = new Random();
for (int i = 0; i < particalcount; i++)
{
Partical partical = new Partical();
partical.position = new Vector2(rand.Next(0, 2000), rand.Next(0, 1000));
partical.oldposition = partical.position;
partical.ID = i;
int x1 = (int)Math.Round((partical.position.X + 5) / 10);
int y1 = (int)Math.Round((partical.position.Y + 5) / 10);
int x2 = (int)Math.Round((partical.position.X - 5) / 10);
int y2 = (int)Math.Round((partical.position.Y - 5) / 10);
solver.Grid[x1, y1].Add(partical.ID);
solver.Grid[x2, y1].Add(partical.ID);
solver.Grid[x1, y2].Add(partical.ID);
solver.Grid[x2, y2].Add(partical.ID);
solver.Particals.Add(partical);
}
canstart = true;
}
}
public class Partical
{
public Vector2 position = new Vector2(0, 0);
public Vector2 oldposition = new Vector2(0, 0);
public Vector2 acceleration = new Vector2(0, 0);
Vector2 zero = new Vector2(0, 0);
public int ID = new int();
public void updatePosition(float sub)
{
Vector2 velocity = position - oldposition;
oldposition = position;
position = position + (velocity * 0.9f) + acceleration * sub;
acceleration = zero;
}
public void accelerate(Vector2 accel)
{
acceleration = acceleration + accel;
}
}
public class Solver
{
public List<Partical> Particals = new List<Partical>();
public List<Vector2> Collision = new List<Vector2>();
public List<int>[,] Grid = new List<int>[2100,1100];
public void update()
{
int subcount = 8;
float sub = 1f / (float)subcount;
for (int i = 0; i < subcount; i++)
{
applyGravity(sub);
updatePositions(sub);
for (int j = 0; j < Collision.Count; j++)
{
solvecolisions((int)Collision[j].X, (int)Collision[j].Y);
}
Collision.Clear();
}
}
public void startupdate()
{
applyGravity(0.5f);
updatePositions(0.5f);
applyGravity(0.5f);
updatePositions(0.5f);
}
void updatePositions(float sub)
{
foreach (Partical partical in Particals)
{
partical.updatePosition(sub);
int x1 = (int)Math.Round((partical.oldposition.X + 5) / 10);
int y1 = (int)Math.Round((partical.oldposition.Y + 5) / 10);
int x2 = (int)Math.Round((partical.oldposition.X - 5) / 10);
int y2 = (int)Math.Round((partical.oldposition.Y - 5) / 10);
Grid[x1,y1].Remove(partical.ID);
Grid[x2,y1].Remove(partical.ID);
Grid[x1,y2].Remove(partical.ID);
Grid[x2,y2].Remove(partical.ID);
x1 = (int)Math.Round((partical.position.X + 5) / 10);
y1 = (int)Math.Round((partical.position.Y + 5) / 10);
x2 = (int)Math.Round((partical.position.X - 5) / 10);
y2 = (int)Math.Round((partical.position.Y - 5) / 10);
Grid[x1,y1].Add(partical.ID);
Grid[x2,y1].Add(partical.ID);
Grid[x1,y2].Add(partical.ID);
Grid[x2,y2].Add(partical.ID);
}
}
void applyGravity(float sub)
{
float gravitystrangth = -0.1f;
foreach (Partical partical in Particals)
{
float a = partical.position.Y;
float b = partical.position.X;
b -= 1000;
a -= 500;
double angle = Math.Atan2(a, b);
float newA = gravitystrangth * (float)(Math.Sin(angle));
float newB = gravitystrangth * (float)(Math.Sin((Math.PI / 180) * 90 - angle));
Vector2 gravity = new Vector2(newB, newA);
partical.accelerate(gravity);
}
}
void solvecolisions(int id1, int id2)
{
Partical part = Particals[id1];
Partical part2 = Particals[id2];
if (part != part2)
{
Vector2 colisionaxis = part.position - part2.position;
float dist = colisionaxis.Length();
if (dist < 10)
{
Vector2 n = colisionaxis / dist;
float delta = 10 - dist;
part.position += 0.5f * delta * n;
part2.position -= 0.5f * delta * n;
}
}
}
public List<Partical> GetParticals()
{
return Particals;
}
}
}
`

You ts list depends on solver.Grid[x,y]. I am sure that some of your code that is not visible on the screen makes some changes of solver.Grid, probably deletes some times, or replaces them. This is what causing the error.

Related

Apple Spawning Inside Snake

I am very new to unity and I made a snake game. However, the apple can sometimes spawn inside the snake. I'm assuming that this needs an if statement like if CreateRandomApple = TailNode then try again but I'm not sure how to code that. Here is my code for the snake and the apple.
void PlacePlayer()
{
playerObj = new GameObject("Player");
SpriteRenderer playerRender = playerObj.AddComponent<SpriteRenderer>();
playerSprite = CreateSprite(playerColor);
playerRender.sprite = (playerSprite);
playerRender.sortingOrder = 1;
playerNode = GetNode(3, 3);
PlacePlayerObject(playerObj, playerNode.worldPosition);
playerObj.transform.localScale = Vector3.one * 1.2f;
tailParent = new GameObject("tailParent");
}
void CreateApple()
{
appleObj = new GameObject("Apple");
SpriteRenderer appleRenderer = appleObj.AddComponent<SpriteRenderer>();
appleRenderer.sprite = CreateSprite(appleColor);
appleRenderer.sortingOrder = 1;
RandomlyPlacedApple();
}
#endregion
#region Update
void MoveTail()
{
Node prevNode = null;
for (int i = 0; i < tail.Count; i++)
{
SpecialNode p = tail[i];
availbleNodes.Add(p.node);
if (i == 0)
{
prevNode = p.node;
p.node = playerNode;
}
else
{
Node prev = p.node;
p.node = prevNode;
prevNode = prev;
}
availbleNodes.Remove(p.node);
PlacePlayerObject(p.obj, p.node.worldPosition);
}
}
#endregion
#region Utilities
bool isTailNode(Node n)
{
for (int i = 0; i < tail.Count; i++)
{
if(tail[i].node == n)
{
return true;
}
}
return false;
}
void PlacePlayerObject(GameObject obj, Vector3 pos)
{
pos += Vector3.one * .5f;
obj.transform.position = pos;
}
void RandomlyPlacedApple()
{
int ran = Random.Range(0, availbleNodes.Count);
Node n = availbleNodes[ran];
PlacePlayerObject(appleObj, n.worldPosition);
appleNode = n;
}
Node GetNode(int x, int y)
{
if (x < 0 || x > MaxWidth - 1 || y < 0 || y > MaxHeight - 1)
return null;
return grid[x, y];
}
SpecialNode CreateTailNode(int x, int y)
{
SpecialNode s = new SpecialNode();
s.node = GetNode(x, y);
s.obj = new GameObject();
s.obj.transform.parent = tailParent.transform;
s.obj.transform.position = s.node.worldPosition;
s.obj.transform.localScale = Vector3.one * .95f;
SpriteRenderer r = s.obj.AddComponent<SpriteRenderer>();
r.sprite = (playerSprite);
r.sortingOrder = 1;
return s;
}
#endregion
}`
This is a simplified version of the script.
Thanks
Since you have an isTailNode function you should be able to continuously generate new apple nodes and check if they are tail nodes. If they are you generate new ones. This can be achieved using a while loop.
void RandomlyPlacedApple()
{
int ran = Random.Range(0, availbleNodes.Count);
while(isTailNode(availbleNodes[ran]))
{
ran = Random.Range(0, availbleNodes.Count);
}
PlacePlayerObject(appleObj, availbleNodes[ran].worldPosition);
appleNode = availbleNodes[ran];
}
Check if it's inside ez
if(apple.location == snake.location){ changeAppleLocation() }

Zoom on Canvas in WPF C#

I implemented Canvas and ToolBar (in WPF C#) and vector graphics editor like Paint almost. I have a problem with the implementation of the Zoom. As I understand the Zoom:
0) I choose the tool ZoomTool;
1) I choose a point on Canvas;
2) I click on it and all the necessary work happens here :
1. Moving (shifting) the selected point to the center of Canvas;
2. Zoom in 2 times (as an example) relative to the center
The problem is the implementation of this work (shift and zoom in), how to do it?
enter image description here
This is my code:
class RecZoomTool : Tool
{
public RecZoomTool()
{
}
public override void MouseDown(Point mousePosition)
{
Point pointDirection = new Point(Creator.CanvasWidth / 2, Creator.CanvasHeight /2);
Creator.ShearingZoom(Point.Subtract(pointDirection, mousePosition));
Creator.Zooming(2);
}
}
then --->
public static void Zooming(double delta)
{
foreach (var figure in Figures)
{
for (int j = 0; j < figure.coordinates.Count; j++)
{
figure.coordinates[j] = new Point(
figure.coordinates[j].X * scaleZoom,
figure.coordinates[j].Y * scaleZoom
);
}
}
// scaleZoom += delta;
}
public static void ShearingZoom(Point dPoint, Point mPoint)
{
foreach (var figure in Figures)
{
Vector delta = Point.Subtract(mPoint, dPoint);
for (int j = 0; j < figure.coordinates.Count; j++)
{
figure.coordinates[j] = new Point(dPoint.X, dPoint.Y);
//counterZoom++;
//delta = Point.Subtract(figure.coordinates[j], dPoint);
figure.coordinates[j] = Point.Add(figure.coordinates[j], delta);
}
offsetPosition += delta;
}
}
Correct answer for every MouseClick:
public override void MouseDown(Point mousePosition)
{
double valueZoom = 2.0;
Point pointDirection = new Point(0.0, 0.0);
Creator.Shifting(Point.Subtract(pointDirection, mousePosition));
Creator.Zooming(valueZoom);
}
And there's in main class:
public static int scaleZoom = 2;
public static Vector offsetPosition = new Vector(0.0, 0.0);
public static int counterZoom = 0;
public static void Zooming(double scaleZoom)
{
foreach (var figure in Figures)
{
for (int j = 0; j < figure.coordinates.Count; j++)
{
figure.coordinates[j] = new Point(
figure.coordinates[j].X * scaleZoom,
figure.coordinates[j].Y * scaleZoom
);
}
}
}
public static void Shifting(Vector delta)
{
offsetPosition = delta / scaleZoom;
foreach (var figure in Figures)
{
for (int j = 0; j < figure.coordinates.Count; j++)
{
figure.coordinates[j] = Point.Add(figure.coordinates[j], offsetPosition);
}
}
}

how can I add more convex hulls in one picture

i'm doing homework in Visual Studio 2017.
I have to create a convex hull and then add more convex hulls to it, without changing others. So I find out how to make one convex hull but I don't know how to add more in this code. I have to create new botton (Add convex hull) in a code and then I don't know how to continue.
Thank you for all your answers.
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
Point zacasna = new Point();
zacasna.X = e.X;
zacasna.Y = e.Y;
seznamTock.Add(zacasna);
pictureBox1.Image = Image.FromFile(file);
using (var g = Graphics.FromImage(pictureBox1.Image))
{
for (int i = 0; i < seznamTock.Count; i++)
{
g.DrawEllipse(barva_tock, seznamTock[i].X, seznamTock[i].Y,
5, 5);
}
pictureBox1.Refresh();
}
}
private List<Point> konveksnaLupina(List<Point> tocka)
{
List<Point> hull = new List<Point>();
Point vPointOnHull = tocka.Where(p => p.X == tocka.Min(min =>
min.X)).First();
Point vEndpoint;
do
{
hull.Add(vPointOnHull);
vEndpoint = tocka[0];
for (int i = 1; i < tocka.Count; i++)
{
if ((vPointOnHull == vEndpoint)
|| (Orientacija(vPointOnHull, vEndpoint, tocka[i]) ==
-1))
{
vEndpoint = tocka[i];
}
}
vPointOnHull = vEndpoint;
}
while (vEndpoint != hull[0]);
return hull;
}
private static int Orientacija(Point p1, Point p2, Point p)
{
// Determinanta
int Orin = (p2.X - p1.X) * (p.Y - p1.Y) - (p.X - p1.X) * (p2.Y -
p1.Y);
if (Orin > 0)
{
return -1; //orientacija v levo
}
if (Orin < 0)
{
return 1; //orientacija v desno
}
return 0; //neutralna orientacija
}
private void button2_Click(object sender, EventArgs e)
{
if (seznamTock.Count < 3)
{
MessageBox.Show("Premalo tock!");
return;
}
List<Point> hull = new List<Point>();
hull = konveksnaLupina(seznamTock);
pictureBox1.Image = Image.FromFile(file);
using (var g = Graphics.FromImage(pictureBox1.Image))
{
for (int j = 0; j < seznamTock.Count; j++)
{
g.DrawEllipse(barva_tock, seznamTock[j].X, seznamTock[j].Y,
5, 5);
}
for (int j = 0; j < hull.Count; j++)
{
Point tocka1 = new Point(hull[j].X, hull[j].Y);
Point tocka2 = new Point(hull[(j + 1) % hull.Count].X,
hull[(j + 1) % hull.Count].Y);
g.DrawLine(barva_kon_lupine, tocka1, tocka2);
}
for (int j = 0; j < hull.Count; j++)
{
g.DrawEllipse(barva_tock_kon_lupine, hull[j].X, hull[j].Y,
`enter code here`5, 5);
}
pictureBox1.Refresh();
}
}
}
add new points in to the new list, but without changing previous figure
You are thinking List<Point> is figure. Well, it's not. It's a list of points. Figures may have more properties and if you have several figures stored as array of points - how would you know which point belong to which figure?
OOP can make it more clear:
abstract class Figure
{
public abstract void Draw(Graphics graphics);
}
class Convex: Figure
{
public List<Point> Points { get; set; }
public Color Color { get; set; } = Color.Black;
... // more properties
public override void Draw(Graphics graphics)
{
if(Points != null)
using(var pen = new Pen(Color))
graphics.DrawLines(pen, Points.ToArray());
}
}
... // more figures
You can hold different figures in List<Figure> and simply add new figure to it:
class Billboard
{
public List<Figure> Figures { get; } = new List<Figure>();
public void Add(Figure figure) => Figures.Add(figure);
... // more methods
}
Redraw:
Billboard _billboard = new Billboard();
void pictureBox1_Paint(object sender, PaintEventArgs e)
{
foreach(var figure in _billboard.Figures)
figure.Draw(e.Graphics);
}
I like Sinatrs approach. But, here's an alternative, just using a collection and your existing code. It's not, the best mod. Think, it does what you want.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
Collection<List<Point>> test = new Collection<List<Point>>();
List<Point> seznamTock = new List<Point>();
Pen barva_tock = new Pen(Color.Blue);
Pen barva_kon_lupine = new Pen(Color.Black);
Pen barva_tock_kon_lupine = new Pen(Color.Yellow);
public Form1()
{
InitializeComponent();
test.Add(seznamTock);
}
private List<Point> konveksnaLupina(List<Point> tocka)
{
List<Point> hull = new List<Point>();
Point vPointOnHull = tocka.Where(p => p.X == tocka.Min(min =>
min.X)).First();
Point vEndpoint;
do
{
hull.Add(vPointOnHull);
vEndpoint = tocka[0];
for (int i = 1; i < tocka.Count; i++)
{
if ((vPointOnHull == vEndpoint)
|| (Orientacija(vPointOnHull, vEndpoint, tocka[i]) ==
-1))
{
vEndpoint = tocka[i];
}
}
vPointOnHull = vEndpoint;
}
while (vEndpoint != hull[0]);
return hull;
}
private static int Orientacija(Point p1, Point p2, Point p)
{
// Determinanta
int Orin = (p2.X - p1.X) * (p.Y - p1.Y) - (p.X - p1.X) * (p2.Y - p1.Y);
return (Orin == 0) ? Orin : ((Orin > 0) ? -1 : 1);
//if (Orin > 0)
//{
// return -1; //orientacija v levo
//}
//if (Orin < 0)
//{
// return 1; //orientacija v desno
//}
//return 0; //neutralna orientacija
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
Point zacasna = new Point();
zacasna.X = e.X;
zacasna.Y = e.Y;
seznamTock.Add(zacasna);
//pictureBox1.Image = Image.FromFile(file);
using (var g = Graphics.FromImage(pictureBox1.Image))
{
for (int i = 0; i < seznamTock.Count; i++) { g.DrawEllipse(barva_tock, seznamTock[i].X, seznamTock[i].Y, 5, 5); }
pictureBox1.Refresh();
}
}
private void button1_Click(object sender, EventArgs e)
{
//if (seznamTock.Count < 3)
//{
// MessageBox.Show("Premalo tock!");
// return;
//}
List<Point> hull = new List<Point>();
hull = konveksnaLupina(seznamTock);
//pictureBox1.Image = Image.FromFile(file);
using (var g = Graphics.FromImage(pictureBox1.Image))
{
for (int j = 0; j < seznamTock.Count; j++)
{
g.DrawEllipse(barva_tock, seznamTock[j].X, seznamTock[j].Y,
5, 5);
}
for (int j = 0; j < hull.Count; j++)
{
Point tocka1 = new Point(hull[j].X, hull[j].Y);
Point tocka2 = new Point(hull[(j + 1) % hull.Count].X,
hull[(j + 1) % hull.Count].Y);
g.DrawLine(barva_kon_lupine, tocka1, tocka2);
}
for (int j = 0; j < hull.Count; j++)
{
g.DrawEllipse(barva_tock_kon_lupine, hull[j].X, hull[j].Y, 5, 5);
}
pictureBox1.Refresh();
test.Add(seznamTock);
seznamTock = new List<Point>();
}
}
}
}

Trying to figure out how to pause and resume in Cocossharp (BouncyGame)

So I'm playing around with the BouncyGame. I made it so that when you start the game you need to press the screen for it to start. I would like to implement this whenever you play a new round as well. I tried to reuse this att the bottom of my code but it made it extremely laggy.
// Register for touch events
var touchListener = new CCEventListenerTouchAllAtOnce();
touchListener.OnTouchesEnded = OnTouchesEnded;
touchListener.OnTouchesMoved = OnTouchesEnded;
AddEventListener(touchListener, this);
}
void OnTouchesEnded(List<CCTouch> touches, CCEvent touchEvent)
{
if (touches.Count > 0)
{
Schedule(RunGameLogic);
scoreLabel.Text = "Score: 0";
paddleSprite.RunAction(new CCMoveTo(.1f, new CCPoint(touches[0].Location.X, paddleSprite.PositionY)));
}
}
I have no idea how to do this, tried for 2 hours with 0 results. Any suggestions are welcome.
Here's the full code.
using System;
using System.Collections.Generic;
using CocosSharp;
using Microsoft.Xna.Framework;
namespace CocosSharpGameTest
{
public class IntroLayer : CCLayerColor
{
// Define a label variable
CCLabel scoreLabel;
CCSprite paddleSprite, ballSprite;
public IntroLayer() : base(CCColor4B.Black)
{
// create and initialize a Label
scoreLabel = new CCLabel("Tap to GO!", "Arial", 80, CCLabelFormat.SystemFont);
// add the label as a child to this Layer
scoreLabel.PositionX = 50;
scoreLabel.PositionY = 1000;
scoreLabel.AnchorPoint = CCPoint.AnchorUpperLeft;
AddChild(scoreLabel);
paddleSprite = new CCSprite("paddle.png");
AddChild(paddleSprite);
ballSprite = new CCSprite("ball.png");
AddChild(ballSprite);
}
protected override void AddedToScene()
{
base.AddedToScene();
// Use the bounds to layout the positioning of our drawable assets
CCRect bounds = VisibleBoundsWorldspace;
// position the label on the center of the screen
paddleSprite.PositionX = 100;
paddleSprite.PositionY = 100;
ballSprite.PositionX = 320;
ballSprite.PositionY = 640;
// Register for touch events
var touchListener = new CCEventListenerTouchAllAtOnce();
touchListener.OnTouchesEnded = OnTouchesEnded;
touchListener.OnTouchesMoved = OnTouchesEnded;
AddEventListener(touchListener, this);
}
void OnTouchesEnded(List<CCTouch> touches, CCEvent touchEvent)
{
if (touches.Count > 0)
{
Schedule(RunGameLogic);
scoreLabel.Text = "Score: 0";
paddleSprite.RunAction(new CCMoveTo(.1f, new CCPoint(touches[0].Location.X, paddleSprite.PositionY)));
}
}
float ballXVelocity;
float ballYVelocity;
// How much to modify the ball's y velocity per second:
const float gravity = 140;
int score = 0;
void RunGameLogic(float frameTimeInSeconds)
{
// This is a linear approximation, so not 100% accurate
ballYVelocity += frameTimeInSeconds * -gravity;
ballSprite.PositionX += ballXVelocity * frameTimeInSeconds;
ballSprite.PositionY += ballYVelocity * frameTimeInSeconds;
bool overlap = ballSprite.BoundingBoxTransformedToParent.IntersectsRect(paddleSprite.BoundingBoxTransformedToParent);
bool movingDown = ballYVelocity < 0;
if (overlap && movingDown)
{
ballYVelocity *= -1;
const float minXVelocity = -300;
const float maxXVelocity = 300;
ballXVelocity = CCRandom.GetRandomFloat(minXVelocity, maxXVelocity);
score++;
scoreLabel.Text = "Score: " + score;
}
float ballRight = ballSprite.BoundingBoxTransformedToParent.MaxX;
float ballLeft = ballSprite.BoundingBoxTransformedToParent.MinX;
float screenRight = VisibleBoundsWorldspace.MaxX;
float screenLeft = VisibleBoundsWorldspace.MinX;
bool shouldReflectXVelocity =
(ballRight > screenRight && ballXVelocity > 0) ||
(ballLeft < screenLeft && ballXVelocity < 0);
if (shouldReflectXVelocity)
{
ballXVelocity *= -1;
}
if (ballSprite.PositionY < VisibleBoundsWorldspace.MinY)
{
ballSprite.PositionX = 320;
ballSprite.PositionY = 640;
ballXVelocity = 0;
ballYVelocity = 0;
ballYVelocity *= -1;
scoreLabel.Text = "Score: 0";
score = 0;
}
}
}
}
Thanks in advance!
Figured it out!
There is an "Unschedule" Method built into Cocossharp.
Ref. https://developer.xamarin.com/api/namespace/CocosSharp/
I just added
Unschedule(RunGameLogic);
at the very en of my RunGameLogic method under
if (ballSprite.PositionY < VisibleBoundsWorldspace.MinY)
So once the ballSprite is out of bounds it will Unschedule what i Scheduled in my OntouchesEnded method. That means the code goes back to listening for touches.
Might have made some errors, but this is as best I could figure it out and it works!

How to get my line to bounce propery on winforms

I have been trying to create a winforms program in C# that illustrate the Mystify screensaver, some how I cant get the line to flow smoothly. I dont know if my calculations or off but I would appreciate a tip please. The lines keep appearing randomly on the form rather than flowing with a shadow or tail.
private bool playButton = false;
private int xP1 = 10;
private int yP1 = 10;
private int xP2 = 100;
private int yP2 = 50;
private int xSpeed = 0;
private int ySpeed = 0;
private int windowHeight = 400;
private int windowWidth = 600;
private int xSpeedChange = 2;
private int ySpeedChange = 2;
private Random rand = new Random();
public SETMystify()
{
InitializeComponent();
}
private void toolStripButton1_Click(object sender, EventArgs e)
{
playButton = true;
}
private void canvas_Paint(object sender, PaintEventArgs e)
{
Graphics paintLine = e.Graphics;
Pen penColor = new Pen(Color.Red, 3);
if (playButton == true)
{
xP1 = rand.Next(0, windowHeight);
yP1 = rand.Next(0, windowWidth);
yP2 = rand.Next(0, windowHeight);
xP2 = rand.Next(0, windowWidth);
xSpeed = rand.Next(5, 10);
ySpeed = rand.Next(5, 10);
xP1 += xSpeed;
yP1 += ySpeed;
xP2 += xSpeed;
yP2 += ySpeed;
}
if (xP1 > windowWidth)
{
xP1 = windowWidth;
xSpeed = xSpeedChange * -1;
}
if (xP1 < 0)
{
xP1 = 0;
xSpeed = xSpeedChange;
}
if (yP1 > windowHeight)
{
yP1 = windowHeight;
ySpeed = ySpeedChange * -1;
}
if (yP1 < 0)
{
yP1 = 0;
ySpeed = ySpeedChange;
}
//-----------------------//
if (xP2 > windowWidth)
{
xP2 = windowWidth;
xSpeed = xSpeedChange * -1;
}
if (xP2 < 0)
{
xP2 = 0;
xSpeed = xSpeedChange;
}
if (yP2 > windowHeight)
{
yP2 = windowHeight;
ySpeed = ySpeedChange * -1;
}
if (yP2 < 0)
{
yP2 = 0;
ySpeed = ySpeedChange;
}
paintLine.DrawLine(penColor, xP1, yP1, xP2, yP2);
canvas.Invalidate();
}
}

Categories

Resources