Orienting an ellipse in 3D space - c#

I am trying to create an ellipse in 3D space. Ive used
https://www.youtube.com/watch?v=mQKGRoV_jBc
https://www.youtube.com/watch?v=Or3fA-UjnwU&t=390s
https://www.youtube.com/watch?v=lKfqi52PqHk
to create an ellipse. Now the ellipse is constructed via a xAxis and a yAxis. I need to move the middlepoint of the ellipse a given distance in a certain direction and then tilt the hole plane on which the ellipse is constructed at a certain angle.
Now my idea is to take the transform.position of the constructing empty and offset it in the direction needed and at the distance needed. The idea goes then further by simply rotating the constructing empty the given angle. Unfortunelty I have 0 clue how to. Ive provided you with the Ellipse class creating the Ellipse and the EllipseRenderer-script so you have an idea whats going on.
[System.Serializable]
public class Ellipse
{
float xAxis;
float yAxis;
public Ellipse(float xAxis, float yAxis)
{
this.xAxis = xAxis;
this.yAxis = yAxis;
}
public Vector2 Evaluate(float orbitalProgression)
{
float angle = Mathf.Deg2Rad * 360 * orbitalProgression;
float x = Mathf.Sin(angle) * xAxis;
float y = Mathf.Cos(angle) * yAxis;
return new Vector2(x, y);
}
}
,
public class OrbitMotion : MonoBehaviour
{
public Transform orbitingObject;
public Ellipse orbitPath;
[Range(0f,1f)]
public float orbitProgress = 0f;
public float orbitPeriod = 3f;
public bool orbitActive = false;
void Start()
{
if (orbitingObject == null)
{
orbitActive = false;
return;
}
SetOrbitingObjectPosition();
StartCoroutine(AnimateOrbit());
}
void SetOrbitingObjectPosition()
{
Vector2 orbitPos = orbitPath.Evaluate(orbitProgress);
orbitingObject.position = new Vector3(orbitPos.x, 0, orbitPos.y);
}
IEnumerator AnimateOrbit()
{
if (orbitPeriod < 0.1f)
{
orbitPeriod = 0.1f;
}
float orbitspeed = 1 / orbitPeriod;
while (orbitActive)
{
orbitProgress += Time.deltaTime * orbitspeed;
orbitProgress %= 1f;
SetOrbitingObjectPosition();
yield return null;
}
}
}
and
[RequireComponent(typeof(LineRenderer))]
public class EllipseRenderer : MonoBehaviour
{
[Range(3, 36)]
public int segments = 7;
public LineRenderer lr;
public Ellipse ellipse;
private void Awake()
{
lr = GetComponent<LineRenderer>();
CalculateEllipse();
}
void CalculateEllipse()
{
Vector3[] points = new Vector3[segments + 1];
for (int i = 0; i < segments; i++)
{
Vector2 position2D = ellipse.Evaluate((float)i / (float)segments);
points[i] = new Vector3(position2D.x, position2D.y, 0);
}
points[segments] = points[0];
lr.positionCount = segments + 1;
lr.SetPositions(points);
}
public Vector3 CalculatePosition()
{
}
private void OnValidate()
{
CalculateEllipse();
}
}

Related

How to check if object is inside terrain area?

I have a plane and when i click on the plane it's spawning objects on the plane area and on the terrain ground.
but i want to do that if the plane or part of it is out of the terrain area that it will disable the spawning part.
This screenshot show the plane above the terrain.
and this screenshot where the plane is out of the terrain area but i can still click on the plane and spawn objects.
This is the spawn objects script :
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class SpawnObjects : MonoBehaviour
{
public GameObject prefabToSpawn;
public Terrain terrain;
public CustomPlane plane;
public GameObject spawnedTerrainObjectsParent;
public GameObject spawnedPlaneObjectsParent;
public bool go = false;
public int numberOfObjects;
public float duration;
public float yOffset = 0.5f;
public bool isParent = true;
private float terrainWidth;
private float terrainLength;
private float xTerrainPos;
private float zTerrainPos;
private float planeWidth;
private float planeLength;
private float xPlanePos;
private float zPlanePos;
private float yValTerrain;
private float yValPlane;
private float randXTerrain;
private float randZTerrain;
private float randXPlane;
private float randZPlane;
private GameObject cube;
private Collider terrainCollider;
void Awake()
{
if (terrain != null)
{
//Get terrain size
terrainWidth = terrain.terrainData.size.x;
terrainLength = terrain.terrainData.size.z;
//Get terrain position
xTerrainPos = terrain.transform.position.x;
zTerrainPos = terrain.transform.position.z;
terrainCollider = terrain.GetComponent<Collider>();
}
if (plane != null)
{
planeWidth = plane.width;
planeLength = plane.length;
xPlanePos = plane.transform.position.x;
zPlanePos = plane.transform.position.z;
}
if (isParent)
{
if(spawnedTerrainObjectsParent == null)
{
spawnedTerrainObjectsParent = GameObject.Find("Spawned Terrain Parent");
}
if(spawnedPlaneObjectsParent == null)
{
spawnedPlaneObjectsParent = GameObject.Find("Spawned Plane Parent");
}
}
Camera.main.transform.position =
new Vector3(plane.GetComponent<Renderer>().bounds.center.x, 635,
plane.GetComponent<Renderer>().bounds.center.z);
if (go)
{
StartCoroutine(Generate());
}
}
IEnumerator Generate()
{
//Generate the Prefab on the generated position
for (int i = 0; i < numberOfObjects; i++)
{
if (terrain != null)
{
//Generate random x,z,y position on the terrain
randXTerrain = UnityEngine.Random.Range(xTerrainPos, xTerrainPos + terrainWidth);
randZTerrain = UnityEngine.Random.Range(zTerrainPos, zTerrainPos + terrainLength);
yValTerrain = Terrain.activeTerrain.SampleHeight(new Vector3(randXTerrain, 0, randZTerrain));
yValTerrain = yValTerrain + yOffset;
GameObject objInstanceTerrain = (GameObject)Instantiate(prefabToSpawn,
new Vector3(randXTerrain, yValTerrain, randZTerrain), Quaternion.identity);
objInstanceTerrain.name = "Terrain Spawned";
if (isParent)
{
objInstanceTerrain.transform.parent = spawnedTerrainObjectsParent.transform;
}
}
if (plane != null)
{
randXPlane = UnityEngine.Random.Range(xPlanePos, xPlanePos + planeWidth);
randZPlane = UnityEngine.Random.Range(zPlanePos, zPlanePos + planeLength);
yValPlane = 0;
yValPlane = yValPlane + yOffset;
GameObject objInstancePlane = (GameObject)Instantiate(prefabToSpawn,
new Vector3(randXPlane, yValPlane, randZPlane), Quaternion.identity);
objInstancePlane.name = "Plane Spawned";
if (isParent)
{
objInstancePlane.transform.parent = spawnedPlaneObjectsParent.transform;
}
}
if (duration > 0)
{
yield return new WaitForSeconds(duration);
}
}
}
private void Update()
{
SpawnThroughPlane();
}
public void SpawnThroughPlane()
{
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (plane.GetComponent<MeshCollider>().Raycast(ray, out hit, Mathf.Infinity))
{
cube = Instantiate(prefabToSpawn);
cube.transform.position = hit.point;
float heightFromTerrain = Terrain.activeTerrain.SampleHeight(hit.point);
var posy = hit.point.y;
posy -= heightFromTerrain;
var newpos = new Vector3(hit.point.x, hit.point.y - posy, hit.point.z);
Instantiate(prefabToSpawn, newpos, Quaternion.identity);
}
}
}
}

How to do Animation to line renderer in Unity C#

Is there any way to add animation to this line renderer? I mean I want to draw a line from Point 1 to point3 the line should move like a progress bar. How to do it in the below script
public class DrawLineRenderer : MonoBehaviour
{
public Transform Point1;
public Transform Point2;
public Transform Point3;
public LineRenderer linerenderer;
public float vertexCount = 12;
public float Point2Ypositio = 2;
// Start is called before the first frame update
void Start()
{
linerenderer.SetWidth(10, 10);
}
// Update is called once per frame
void Update()
{
}
public void buttonPress()
{
Point2.transform.position = new Vector3((Point1.transform.position.x + Point3.transform.position.x)/2, Point2Ypositio, (Point1.transform.position.z + Point3.transform.position.z) /2);
var pointList = new List<Vector3>();
for(float ratio = 0;ratio<=1;ratio+= 1/vertexCount)
{
var tangent1 = Vector3.Lerp(Point1.position, Point2.position, ratio);
var tangent2 = Vector3.Lerp(Point2.position, Point3.position, ratio);
var curve = Vector3.Lerp(tangent1, tangent2, ratio);
pointList.Add(curve);
}
linerenderer.positionCount = pointList.Count;
linerenderer.SetPositions(pointList.ToArray());
}
}

Why the transform is not moving to the new radius when changing the radius at runtime?

if dc is not null i'm using a radius from another script and it's working fine when i'm changing the radius value in the DrawCircle script the transform in RotateAroundTarget is moving smooth to the new radius.
but if dc variable is null i want to use the local radius variable for setting the radius in runtime but when changing the radius the transform is not moving to the new radius.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotateAroundTarget : MonoBehaviour
{
public Transform target;
public float rotatingSpeed;
public float movingSpeed;
public Vector3 axis;
public bool randomHeight;
public float setRandomHeight = 1;
public float radius;
public DrawCircle dc;
private float lastRadius;
private bool move = false;
private float t = 0.0f;
public float upperLimit, lowerLimit, delay;
private float prevHeight;
private Vector3 radiusPosition;
private void Start()
{
if (dc != null)
{
lastRadius = dc.xRadius;
}
else
{
lastRadius = radius;
}
move = true;
}
private void Update()
{
if (dc != null)
{
radiusPosition = new Vector3(target.position.x, target.position.y, dc.xRadius);
}
else
{
radiusPosition = new Vector3(target.position.x, target.position.y, radius);
}
if (move == false)
{
transform.RotateAround(target.position, axis, rotatingSpeed * Time.deltaTime);
t += Time.deltaTime;
if (t > delay)
{
prevHeight = setRandomHeight;
setRandomHeight = Random.Range(lowerLimit, upperLimit);
t = 0;
}
var tt = transform.position;
tt.y = Mathf.Lerp(prevHeight, setRandomHeight, t);
transform.position = tt;
}
if (dc != null)
{
if (lastRadius != dc.xRadius)
{
move = true;
lastRadius = dc.xRadius;
}
}
else
{
if (lastRadius != radius)
{
move = true;
lastRadius = radius;
}
}
if (move)
{
if (transform.position != radiusPosition)
{
float step = movingSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position,
radiusPosition, step);
}
else
{
move = false;
}
}
}
}

How can I create a manager script to control all drawn circles at once?

The first script is for drawing the circle:
When I attach this script to a gameobject it's drawing a circle around the object.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[RequireComponent(typeof(LineRenderer))]
public class DrawCircle : MonoBehaviour
{
[Range(0, 50)]
public int segments = 50;
[Range(1, 50)]
public float xradius = 5;
[Range(1, 50)]
public float yradius = 5;
[Range(-10, 10)]
public float height = 0;
public bool changeBothRadius = false;
[Range(0.1f, 2)]
public float lineThickness = 0.1f;
public bool minimumRadius = false;
private LineRenderer line;
void Start()
{
line = gameObject.GetComponent<LineRenderer>();
line.positionCount = segments + 1;
line.useWorldSpace = false;
}
void Update()
{
line.startWidth = lineThickness;
line.endWidth = lineThickness;
CreatePoints();
}
void CreatePoints()
{
float x;
float z;
float angle = 20;
for (int i = 0; i < (segments + 1); i++)
{
x = Mathf.Sin(Mathf.Deg2Rad * angle) * xradius;
z = Mathf.Cos(Mathf.Deg2Rad * angle) * yradius;
line.SetPosition(i, new Vector3(x, height, z));
angle += (360f / segments + 1);
}
}
}
Now I created a manager script that should control all the circles at once:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CirclesManager : MonoBehaviour
{
public GameObject[] objectsToAddCircles;
[Range(0, 50)]
public int segments = 50;
[Range(1, 50)]
public float xradius = 5;
[Range(1, 50)]
public float yradius = 5;
[Range(-10, 10)]
public float height = 0;
public bool changeBothRadius = false;
[Range(0.1f, 2)]
public float lineThickness = 0.1f;
public bool minimumRadius = false;
void Start()
{
for (int i = 0; i < objectsToAddCircles.Length; i++)
{
objectsToAddCircles[i].AddComponent<DrawCircle>();
objectsToAddCircles[i].AddComponent<LineRenderer>();
}
}
void Update()
{
for (int i = 0; i < objectsToAddCircles.Length; i++)
{
var lr = objectsToAddCircles[i].GetComponent<LineRenderer>();
lr.startWidth = lineThickness;
lr.endWidth = lineThickness;
var dc = objectsToAddCircles[i].GetComponent<DrawCircle>();
dc.segments = segments;
dc.xradius = xradius;
dc.yradius = yradius;
dc.height = height;
dc.changeBothRadius = changeBothRadius;
dc.minimumRadius = minimumRadius;
}
}
}
So now each object have the LineRenderer component and the DrawCircle script and now the CirclesManager script is working on all objects fine but if I try to change individual object settings it will not change. For example I can change the xrdaius or yradius sliders in the manager script but if I try to change them in a specific object the sliders won't move will not change.
Can't figure out why the manager script is working but not each individual object with the script and LineRenderer.
In CirclesManager class in Update you have these lines:
dc.xradius = xradius;
dc.yradius = yradius;
No matter where and how you change individual DrawCircle instance radius, these lines would always overwrite those values.
I don`t know what kind of behaviour you want to archive but you can create a bool array so you can manually set which circles would be driven by CirclesManager and which circles would use their own values:
// you can change it in the inspector which is handy
// if i'th value of this array is false
// then i'th CircleDrawer GameObject in objectsToAddCircles array
// won't be affected by this manager
public bool changableCircle[];
void Start() {
// your code
changableCircle = new bool[objectsToAddCircles.Length];
}
void Update() {
for(...) {
// values which are always overwritten by manager
if(changableCircle[i]) {
// values which you don't want to be changed by this manager
}
}
}

XNA game not launching under very strange conditions

First thing to get out of the way, sorry if I'm missing something (very) obvious, I'm still kinda new at this.
Anyway, I've been working on an asteroids clone in XNA, and for some reason it would occasionally not start if I hit the Start Debugging button. I tracked the problem to my AsteroidsManager class, which takes an int of initial asteroids to generate, minimum and maximum velocities and rotational velocites, and two texture lists for asteroids and particles. Now the weirdness:
temp = new AsteroidManager(1, 20, 50, 1, 2, asteroids, particles, true); //With this constructor, the game always starts fine...
But if I crank up the number of initial asteroids:
temp = new AsteroidManager(10, 20, 50, 1, 2, asteroids, particles, true); //This seems to start about 1/3 times in the Visual Studio debugger, but if I launch it without debugging or from the bin folder, it works fine.
And lastly, if I set the asteroids to more than ~20, it never starts in the debugger, and if I try to start it from the folder, the process appears in the task manager, but nothing ever happens. Or it just crashes on launch. I honestly have no idea what's causing this, and will gladly provide any code if needed, but here's what I think is relevant:
Full AsteroidManager:
public class AsteroidManager
{
#region Declarations
public List<GameObject> Asteroids { get; set; }
public bool RegenerateAsteroids { get; set; }
public readonly int InitialAsteroids;
public readonly float MinVelocity;
public readonly float MaxVelocity;
public readonly float MinRotationalVelocity; //in degrees
public readonly float MaxRotationalVelocity; //in degrees
public readonly List<Texture2D> Textures;
public readonly List<Texture2D> ExplosionParticleTextures;
List<ParticleEmitter> emitters;
Random rnd;
const int MINPARTICLES = 50;
const int MAXPARTICLES = 200;
const int PARTICLEFTL = 40;
#endregion
public AsteroidManager(
int initialAsteroids,
float minVel,
float maxVel,
float minRotVel,
float maxRotVel,
List<Texture2D> textures,
List<Texture2D> explosionParticleTextures,
bool regenAsteroids)
{
rnd = new Random();
InitialAsteroids = initialAsteroids;
MinVelocity = minVel;
MaxVelocity = maxVel;
MinRotationalVelocity = minRotVel;
MaxRotationalVelocity = maxRotVel;
Textures = textures;
ExplosionParticleTextures = explosionParticleTextures;
RegenerateAsteroids = regenAsteroids;
Asteroids = new List<GameObject>();
emitters = new List<ParticleEmitter>();
for (int i = 0; i < InitialAsteroids; i++)
addAsteroid();
}
public void Update(GameTime gameTime)
{
for (int i = 0; i < Asteroids.Count; i++)
Asteroids[i].Update(gameTime);
for (int i = 0; i < emitters.Count; i++)
emitters[i].Update(gameTime);
if (Asteroids.Count < InitialAsteroids && RegenerateAsteroids)
addAsteroid();
}
public void Draw(SpriteBatch spriteBatch)
{
for (int i = 0; i < Asteroids.Count; i++)
Asteroids[i].Draw(spriteBatch);
for (int i = 0; i < emitters.Count; i++)
emitters[i].Draw(spriteBatch);
}
public void DestroyAsteroid(GameObject asteroid)
{
int x = rnd.Next(MINPARTICLES, MAXPARTICLES);
List<Color> colors = new List<Color>();
colors.Add(Color.White);
emitters.Add(new ParticleEmitter( //TODO: Test
x,
asteroid.WorldCenter,
ExplosionParticleTextures,
colors,
PARTICLEFTL,
true,
1,
x,
1f,
0.3f,
0f,
180f));
Asteroids.Remove(asteroid);
}
protected void addAsteroid()
{
GameObject tempAsteroid;
bool isOverlap = false;
do //Do-While to ensure that the asteroid gets generated at least once
{
Texture2D text = Textures.PickRandom<Texture2D>();
float rot = MathHelper.ToRadians((float)rnd.NextDouble(0f, 359f));
float rotVel = MathHelper.ToRadians((float)rnd.NextDouble(MinRotationalVelocity, MaxRotationalVelocity));
int colRadius = (((text.Width / 2) + (text.Height / 2)) / 2); //Get the mean of text's height & width
Vector2 vel = Vector2.Multiply( //calculate a random velocity
rot.RotationToVectorFloat(),
(float)rnd.NextDouble(MinVelocity, MaxVelocity));
Vector2 worldPos = new Vector2(
rnd.Next(Camera.WorldRectangle.X, Camera.WorldRectangle.Width),
rnd.Next(Camera.WorldRectangle.Y, Camera.WorldRectangle.Height));
tempAsteroid = new GameObject( //init a temporary asteroid to check for overlaps
text, worldPos, vel, Color.White, false, rot, rotVel, 1f, 0f, colRadius);
foreach (GameObject asteroid in Asteroids)
{
if (tempAsteroid.BoundingBox.Intersects(asteroid.BoundingBox))
{
isOverlap = true;
break;
}
}
} while (isOverlap); //if overlapping, loop
Asteroids.Add(tempAsteroid); //add the temp asteroid
}
}
Full GameObject:
public class GameObject
{
#region Declarations
public Texture2D Texture { get; set; }
public Vector2 Origin { get; set; }
public Color TintColor { get; set; }
public float Rotation { get; set; } //radians
public float RotationalVelocity { get; set; }
public float Scale { get; set; }
public float Depth { get; set; }
public bool Active { get; set; }
public SpriteEffects Effects { get; set; }
public Vector2 WorldLocation { get; set; }
public Vector2 Velocity { get; set; }
public int CollisionRadius { get; set; } //Radius for bounding circle collision
public int BoundingXPadding { get; set; }
public int BoundingYPadding { get; set; } //Padding for bounding box collision
public int TotalFrames
{
get //simple get
{ return totalFrames; }
set //check if given totalFrames is in possible range
{
if (value <= (Rows * Columns))
totalFrames = value;
else
throw new ArgumentOutOfRangeException();
}
} //Used in spritesheet animation
private int totalFrames;
public int CurrentFrame
{
get { return currentFrame; }
set
{
currentFrame = (int)MathHelper.Clamp(value, 0, totalFrames);
}
}
private int currentFrame;
public int Rows { get; set; }
public int Columns { get; set; }
public bool Animating { get; set; }
public float RotationDegrees
{
get { return MathHelper.ToDegrees(Rotation); }
set { Rotation = MathHelper.ToRadians(value); }
}
public float RotationVelocityDegrees
{
get { return MathHelper.ToDegrees(RotationalVelocity); }
set { RotationalVelocity = MathHelper.ToRadians(value); }
}
public const float VELOCITYSCALAR = 1.0f / 60.0f; //Default to 60fps standard movement
#endregion
#region Properties
public int GetWidth { get { return Texture.Width / Columns; } } //Width of a frame
public int GetHeight { get { return Texture.Height / Rows; } } //Height of a frame
public int GetRow { get { return (int)((float)CurrentFrame / (float)Columns); } } //Current row
public int GetColumn { get { return CurrentFrame % Columns; } } //Current column
public Vector2 SpriteCenter
{ get { return new Vector2(GetWidth / 2, GetHeight / 2); } } //Get this Sprite's center
public Rectangle WorldRectangle //get rectangle in world coords with width of sprite
{
get
{
return new Rectangle(
(int)WorldLocation.X,
(int)WorldLocation.Y,
GetWidth,
GetHeight);
}
}
public Rectangle BoundingBox //get bounding box for use in collision detection
{
get
{
return new Rectangle( //Get bounding box with respect to padding values
(int)WorldLocation.X + BoundingXPadding,
(int)WorldLocation.Y + BoundingYPadding,
GetWidth - (BoundingXPadding * 2),
GetHeight - (BoundingYPadding * 2));
}
}
public Vector2 ScreenLocation
{ get { return Camera.GetLocalCoords(WorldLocation); } } //get screen coordinates
public Rectangle ScreenRectangle
{ get { return Camera.GetLocalCoords(WorldRectangle); } } //get screen rectangle
public Vector2 WorldCenter
{
get { return WorldLocation + SpriteCenter; }
set { WorldLocation = value - SpriteCenter; }
} //gets/sets the center of the sprite in world coords
public Vector2 ScreenCenter
{ get { return Camera.GetLocalCoords(WorldLocation + SpriteCenter); } } //returns the center in screen coords
#endregion
public GameObject( //main constructor, /w added optional parameters and call to SpriteBase init
Texture2D texture,
Vector2 worldLocation,
Vector2 velocity,
Color tintColor,
bool animating = false,
float rotation = 0f, //default to no rotation
float rotationalVelocity = 0f,
float scale = 1f, //default to 1:1 scale
float depth = 0f, //default to 0 layerDepth
int collisionRadius = 0, //collision radius used in bounding circle collision, default to 0 or no bounding circle
int xPadding = 0, //amount of x padding, used in bounding box collision, default to 0, or no bounding box
int yPadding = 0, //amount of y padding, used in bounding box collision, default to 0, or no bounding box
SpriteEffects effects = SpriteEffects.None,
int totalFrames = 0,
int rows = 1,
int columns = 1)
{
if (texture == null) { throw new NullReferenceException("Null texture reference."); }
Texture = texture; //assign parameters
WorldLocation = worldLocation;
TintColor = tintColor;
Rotation = rotation;
RotationalVelocity = rotationalVelocity;
Scale = scale;
Depth = depth;
Effects = effects;
Velocity = velocity;
Animating = animating;
Active = true;
BoundingXPadding = xPadding; BoundingYPadding = yPadding; CollisionRadius = collisionRadius; //assign collision data
Rows = rows; Columns = columns; this.TotalFrames = totalFrames; //assign animation data
Origin = SpriteCenter; //assign origin to the center of a frame
}
#region Methods
public virtual void Update(GameTime gameTime)
{
if (Active) //if object is active
{
WorldLocation += Velocity * (1f / 60f);
Rotation += RotationalVelocity; //Rotate according to the velocity
//Move by Velocity times a roughly 60FPS scalar
if (TotalFrames > 1 && Animating)
{
CurrentFrame++;
if (CurrentFrame >= TotalFrames)
CurrentFrame = 0; //Loop animation
}
if (Camera.IsObjectInWorld(this.WorldRectangle) == false)
{
if (Camera.LOOPWORLD) //if world is looping and the object is out of bounds
{
Vector2 temp = WorldCenter; //temporary Vector2 used for updated position
//X-Axis Component
if (WorldCenter.X > Camera.WorldRectangle.Width)
temp.X = Camera.WorldRectangle.X - (GetWidth / 2); //If X is out of bounds to the right, move X to the left side
if (WorldCenter.X < Camera.WorldRectangle.X)
temp.X = Camera.WorldRectangle.Width + (GetWidth / 2); //If X is out of bound to the left, move X to the right side
//Y-Axis Component
if (WorldCenter.Y > Camera.WorldRectangle.Height)
temp.Y = Camera.WorldRectangle.Y - (GetHeight / 2); //If Y is out of bounds to the bottom, move Y to the top
if (WorldCenter.Y < Camera.WorldRectangle.Y)
temp.Y = Camera.WorldRectangle.Height + (GetHeight / 2); //If Y is out of bounds to the top, move Y to the bottom
WorldCenter = temp; //Assign updated position
}
if (Camera.LOOPWORLD == false)
{
Active = false; //if the object is outside the world but the LOOPWORLD constant is false, set inactive
}
}
}
}
public virtual void Draw(SpriteBatch spriteBatch)
{
if (Active)
{
if (TotalFrames > 1 && Camera.IsObjectVisible(WorldRectangle)) //if multi-frame animation & object is visible
{
Rectangle sourceRectangle = new Rectangle(GetWidth * GetColumn,
GetHeight * GetRow, GetWidth, GetHeight); //get source rectangle to use
spriteBatch.Draw(
Texture,
ScreenCenter,
sourceRectangle, //use generated source rectangle
TintColor,
Rotation,
Origin,
Scale,
Effects,
Depth);
}
else //if single frame sprite
{
if (Camera.IsObjectVisible(WorldRectangle)) //check if sprite is visible to camera
{
spriteBatch.Draw(
Texture,
ScreenCenter, //center of the sprite in local coords
null, //full sprite
TintColor,
Rotation,
Origin,
Scale,
Effects, //spriteeffects
Depth); //layerdepth
}
}
}
}
public bool IsBoxColliding(Rectangle obj) //bounding box collision test
{
return BoundingBox.Intersects(obj);
}
public bool IsBoxColliding(GameObject obj) //overload of previous which takes a GameObject instead of a rectangle
{
if (BoundingBox.Intersects(obj.BoundingBox))
return true;
else
return false;
}
public bool IsCircleColliding(Vector2 objCenter, float objRadius)
{
if (Vector2.Distance(WorldCenter, objCenter) <
(CollisionRadius + objRadius)) //if the distance between centers is greater than the sum
return true; //of the radii, collision has occurred
else
return false; //if not, return false
}
public bool IsCircleColliding(GameObject obj) //overload of previous which takes a GameObject instead of loose values
{
if (Vector2.Distance(this.WorldCenter, obj.WorldCenter) <
(CollisionRadius + obj.CollisionRadius))
return true;
else
return false;
}
public void RotateTo(Vector2 point) //rotates the GameObject to a point
{
Rotation = (float)Math.Atan2(point.Y, point.X);
}
protected Vector2 rotationToVector()
{
return Rotation.RotationToVectorFloat();
} //local version of extension method
#endregion
}
Game1 Draw:
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin(); //BEGIN SPRITE DRAW
fpsDisplay.Draw(spriteBatch);
temp.Draw(spriteBatch);
spriteBatch.End(); //END SPRITE DRAW
base.Draw(gameTime);
}
Game1 Update:
protected override void Update(GameTime gameTime)
{
InputHandler.Update(); //update InputHandler
if (InputHandler.IsKeyDown(Keys.Left))
Camera.Position += new Vector2(-3f, 0f);
if (InputHandler.IsKeyDown(Keys.Right))
Camera.Position += new Vector2(3f, 0f);
if (InputHandler.IsKeyDown(Keys.Up))
Camera.Position += new Vector2(0f, -3f);
if (InputHandler.IsKeyDown(Keys.Down))
Camera.Position += new Vector2(0f, 3f);
fpsDisplay.Value = (int)Math.Round(1 / gameTime.ElapsedGameTime.TotalSeconds, 0);
//calculate framerate to the nearest int
temp.Update(gameTime);
base.Update(gameTime);
}
I would guess that your overlapping code is never finding a spot to place the asteroid. It enters a near-infinite (or possibly infinite if space is covered properly) loop that never exits. You could use a counter that given a number of attempts, it just "gives up". Or you can increase the max size of the playing area they can spawn in, or decrease their size; this would reduce the likelyhood of such an infinite loop from occurring, but not make it impossible given enough asteroids.
int attempts = 0;
do //Do-While to ensure that the asteroid gets generated at least once
{
attempts++;
...
foreach (GameObject asteroid in Asteroids)
{
if (tempAsteroid.BoundingBox.Intersects(asteroid.BoundingBox))
{
isOverlap = true;
break;
}
}
} while (isOverlap && attempts < 20); //if overlapping, loop, give up after 20 tries
if (attempts == 20)
{
//log it! Or fix it, or something!
}
Even if you "fix" this by increasing the game size or reducing the asteroid size, I still suggest you make it run a maximum number of times to avoid infinite loops.

Categories