Edit: Link to Question on GameDev SE: https://gamedev.stackexchange.com/questions/51656/implementing-water-effects-splashes-into-xna-4-0-game
I am creating a 2D XNA game and came across a tutorial on adding water effects (splashes) to an XNA game but after implementing it into my game I can't get it to scale down. Currently it takes up the entire screen.
The Water class looks like this
class Water
{
struct WaterColumn
{
public float TargetHeight;
public float Height;
public float Speed;
public void Update(float dampening, float tension)
{
float x = TargetHeight - Height;
Speed += tension * x - Speed * dampening;
Height += Speed;
}
}
PrimitiveBatch pb;
WaterColumn[] columns = new WaterColumn[201];
static Random rand = new Random();
public float Tension = 0.025f;
public float Dampening = 0.025f;
public float Spread = 0.25f;
RenderTarget2D metaballTarget, particlesTarget;
SpriteBatch spriteBatch;
AlphaTestEffect alphaTest;
Texture2D particleTexture;
private float Scale { get { return spriteBatch.GraphicsDevice.Viewport.Width / (columns.Length - 1f); } }
List<Particle> particles = new List<Particle>();
class Particle
{
public Vector2 Position;
public Vector2 Velocity;
public float Orientation;
public Particle(Vector2 position, Vector2 velocity, float orientation)
{
Position = position;
Velocity = velocity;
Orientation = orientation;
}
}
public Water(GraphicsDevice device, Texture2D particleTexture)
{
pb = new PrimitiveBatch(device);
this.particleTexture = particleTexture;
spriteBatch = new SpriteBatch(device);
metaballTarget = new RenderTarget2D(device, device.Viewport.Width, device.Viewport.Height);
particlesTarget = new RenderTarget2D(device, device.Viewport.Width, device.Viewport.Height);
alphaTest = new AlphaTestEffect(device);
alphaTest.ReferenceAlpha = 175;
var view = device.Viewport;
alphaTest.Projection = Matrix.CreateTranslation(-0.5f, -0.5f, 0) *
Matrix.CreateOrthographicOffCenter(0, view.Width, view.Height, 0, 0, 1);
for (int i = 0; i < columns.Length; i++)
{
columns[i] = new WaterColumn()
{
Height = 240,
TargetHeight = 240,
Speed = 0
};
}
}
// Returns the height of the water at a given x coordinate.
public float GetHeight(float x)
{
if (x < 0 || x > 800)
return 240;
return columns[(int)(x / Scale)].Height;
}
void UpdateParticle(Particle particle)
{
const float Gravity = 0.3f;
particle.Velocity.Y += Gravity;
particle.Position += particle.Velocity;
particle.Orientation = GetAngle(particle.Velocity);
}
public void Splash(float xPosition, float speed)
{
int index = (int)MathHelper.Clamp(xPosition / Scale, 0, columns.Length - 1);
for (int i = Math.Max(0, index - 0); i < Math.Min(columns.Length - 1, index + 1); i++)
columns[index].Speed = speed;
CreateSplashParticles(xPosition, speed);
}
private void CreateSplashParticles(float xPosition, float speed)
{
float y = GetHeight(xPosition);
if (speed > 120)
{
for (int i = 0; i < speed / 8; i++)
{
Vector2 pos = new Vector2(xPosition, y) + GetRandomVector2(40);
Vector2 vel = FromPolar(MathHelper.ToRadians(GetRandomFloat(-150, -30)), GetRandomFloat(0, 0.5f * (float)Math.Sqrt(speed)));
CreateParticle(pos, vel);
}
}
}
private void CreateParticle(Vector2 pos, Vector2 velocity)
{
particles.Add(new Particle(pos, velocity, 0));
}
private Vector2 FromPolar(float angle, float magnitude)
{
return magnitude * new Vector2((float)Math.Cos(angle), (float)Math.Sin(angle));
}
private float GetRandomFloat(float min, float max)
{
return (float)rand.NextDouble() * (max - min) + min;
}
private Vector2 GetRandomVector2(float maxLength)
{
return FromPolar(GetRandomFloat(-MathHelper.Pi, MathHelper.Pi), GetRandomFloat(0, maxLength));
}
private float GetAngle(Vector2 vector)
{
return (float)Math.Atan2(vector.Y, vector.X);
}
public void Update()
{
for (int i = 0; i < columns.Length; i++)
columns[i].Update(Dampening, Tension);
float[] lDeltas = new float[columns.Length];
float[] rDeltas = new float[columns.Length];
// do some passes where columns pull on their neighbours
for (int j = 0; j < 8; j++)
{
for (int i = 0; i < columns.Length; i++)
{
if (i > 0)
{
lDeltas[i] = Spread * (columns[i].Height - columns[i - 1].Height);
columns[i - 1].Speed += lDeltas[i];
}
if (i < columns.Length - 1)
{
rDeltas[i] = Spread * (columns[i].Height - columns[i + 1].Height);
columns[i + 1].Speed += rDeltas[i];
}
}
for (int i = 0; i < columns.Length; i++)
{
if (i > 0)
columns[i - 1].Height += lDeltas[i];
if (i < columns.Length - 1)
columns[i + 1].Height += rDeltas[i];
}
}
foreach (var particle in particles)
UpdateParticle(particle);
particles = particles.Where(x => x.Position.X >= 0 && x.Position.X <= 800 && x.Position.Y - 5 <= GetHeight(x.Position.X)).ToList();
}
public void DrawToRenderTargets()
{
GraphicsDevice device = spriteBatch.GraphicsDevice;
device.SetRenderTarget(metaballTarget);
device.Clear(Color.Transparent);
// draw particles to the metaball render target
spriteBatch.Begin(0, BlendState.Additive);
foreach (var particle in particles)
{
Vector2 origin = new Vector2(particleTexture.Width, particleTexture.Height) / 2f;
spriteBatch.Draw(particleTexture, particle.Position, null, Color.White, particle.Orientation, origin, 2f, 0, 0);
}
spriteBatch.End();
// draw a gradient above the water so the metaballs will fuse with the water's surface.
pb.Begin(PrimitiveType.TriangleList);
const float thickness = 20;
float scale = Scale;
for (int i = 1; i < columns.Length; i++)
{
Vector2 p1 = new Vector2((i - 1) * scale, columns[i - 1].Height);
Vector2 p2 = new Vector2(i * scale, columns[i].Height);
Vector2 p3 = new Vector2(p1.X, p1.Y - thickness);
Vector2 p4 = new Vector2(p2.X, p2.Y - thickness);
pb.AddVertex(p2, Color.White);
pb.AddVertex(p1, Color.White);
pb.AddVertex(p3, Color.Transparent);
pb.AddVertex(p3, Color.Transparent);
pb.AddVertex(p4, Color.Transparent);
pb.AddVertex(p2, Color.White);
}
pb.End();
// save the results in another render target (in particlesTarget)
device.SetRenderTarget(particlesTarget);
device.Clear(Color.Transparent);
spriteBatch.Begin(0, null, null, null, null, alphaTest);
spriteBatch.Draw(metaballTarget, Vector2.Zero, Color.White);
spriteBatch.End();
// switch back to drawing to the backbuffer.
device.SetRenderTarget(null);
}
public void Draw()
{
Color lightBlue = new Color(0.2f, 0.5f, 1f);
// draw the particles 3 times to create a bevelling effect
spriteBatch.Begin();
spriteBatch.Draw(particlesTarget, -Vector2.One, new Color(0.8f, 0.8f, 1f));
spriteBatch.Draw(particlesTarget, Vector2.One, new Color(0f, 0f, 0.2f));
spriteBatch.Draw(particlesTarget, Vector2.Zero, lightBlue);
spriteBatch.End();
// draw the waves
pb.Begin(PrimitiveType.TriangleList);
Color midnightBlue = new Color(0, 15, 40) * 0.9f;
lightBlue *= 0.8f;
float bottom = spriteBatch.GraphicsDevice.Viewport.Height;
float scale = Scale;
for (int i = 1; i < columns.Length; i++)
{
Vector2 p1 = new Vector2((i - 1) * scale, columns[i - 1].Height);
Vector2 p2 = new Vector2(i * scale, columns[i].Height);
Vector2 p3 = new Vector2(p2.X, bottom);
Vector2 p4 = new Vector2(p1.X, bottom);
pb.AddVertex(p1, lightBlue);
pb.AddVertex(p2, lightBlue);
pb.AddVertex(p3, midnightBlue);
pb.AddVertex(p1, lightBlue);
pb.AddVertex(p3, midnightBlue);
pb.AddVertex(p4, midnightBlue);
}
pb.End();
}
}
Then in the Game1.cs I have the following
LoadContent method
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
font = Content.Load<SpriteFont>("Font");
particleImage = Content.Load<Texture2D>("metaparticle");
backgroundImage = Content.Load<Texture2D>("sky");
rockImage = Content.Load<Texture2D>("rock");
water = new Water(GraphicsDevice, particleImage);
.
.
.
}
In my update method I have the following (along with other code for the game, i am just showing water part)
protected override void Update(GameTime gameTime)
{
lastKeyState = keyState;
keyState = Keyboard.GetState();
lastMouseState = mouseState;
mouseState = Mouse.GetState();
water.Update();
Vector2 mousePos = new Vector2(mouseState.X, mouseState.Y);
// if the user clicked down, create a rock.
if (lastMouseState.LeftButton == ButtonState.Released && mouseState.LeftButton == ButtonState.Pressed)
{
rock = new Rock
{
Position = mousePos,
Velocity = (mousePos - new Vector2(lastMouseState.X, lastMouseState.Y)) / 5f
};
}
// update the rock if it exists
if (rock != null)
{
if (rock.Position.Y < 240 && rock.Position.Y + rock.Velocity.Y >= 240)
water.Splash(rock.Position.X, rock.Velocity.Y * rock.Velocity.Y * 5);
rock.Update(water);
if (rock.Position.Y > GraphicsDevice.Viewport.Height + rockImage.Height)
rock = null;
}
Then in the Draw method I have the following (when the active enum is InGame)
case ActiveScreen.InGame:
water.DrawToRenderTargets();
level.Draw(gameTime, spriteBatch);
DrawHud();
spriteBatch.Begin();
spriteBatch.Draw(backgroundImage, Vector2.Zero, Color.White);
if (rock != null)
rock.Draw(spriteBatch, rockImage);
spriteBatch.End();
water.Draw();
break;
My problem is this obviously takes up the entire screen. I realise why it takes up the entire screen but I can't figure out how to scale it down and set it on a fixed location in the game. If anyone could read through this and direct me towards how I would go about scaling this down successfully, I'd greatly appreciate it.
Notice that
private float Scale { get { return spriteBatch.GraphicsDevice.Viewport.Width / (columns.Length - 1f); } }
creates a Scale corresponding to the entire screen. And in both your Draw() and DrawToRenderTargets() methods
Vector2 p1 = new Vector2((i - 1) * scale, columns[i - 1].Height);
Vector2 p2 = new Vector2(i * scale, columns[i].Height);
which means that the top of the vectors (water columns) will start from the beginning of the screen. That's where you need to make change of.
Related
I have not used any of this in class but its still a requirement on our project and I'm getting a bit squeezed.
Summarized: I have to do a pacman game in 2D using the monogame extension on Visual Studio, language is C# and the problem is occuring when I try to move the ghosts, creating the autonomous moviment, I can not wrap my head around a solution so, here's what I got:
float dist = Vector2.Distance(position.ToVector2(), targetPosition.ToVector2());
if (dist <= 1)
{
List<Direction> availableDirections = new List<Direction>();
foreach (var dir in Surroundings)
if (game1.Board.board[targetPosition.X / (Game1.outputTileSize) + dir.Value.X, targetPosition.Y / (Game1.outputTileSize) + dir.Value.Y] == ' ')
availableDirections.Add(dir.Key);
if (availableDirections.Count == 0) return;
availableDirections = availableDirections.OrderBy(dir =>
{
float distP1 = Vector2.Distance(targetPosition.ToVector2() + Surroundings[dir].ToVector2() * Game1.outputTileSize, game1.Player.position.ToVector2());
return distP1;
}).ToList();
direction = availableDirections[0];
direction = Surroundings[availableDirections.Count - 1];
targetPosition = targetPosition + availableDirections[direction].Game1.outputTileSize;
}
else
{
//Position is not the same, move the guy
Vector2 vec = targetPosition.ToVector2() - position.ToVector2();
vec.Normalize();
position = (position.ToVector2() + vec).ToPoint();
//Incrementar frame
if ((position.X + position.Y) % 4 == 0)
frame++;
if (frame > 1) frame = -1;
}
I've tried to instantiate a different kind of list still using the dictionary,but the issue is that it's not recognizing the position on the list as an integer and it clashes. Here's the rest of the code that's relevant to understand the way everything connects:
namespace MsPacMan
{
public class Ghost : DrawableGameComponent
{
//enumeradores
enum Orientation { Horizontal, Vertical }
enum Direction { Up, Down, Left, Right }
#region variables
private Texture2D texture;
private SpriteBatch spriteBatch;
private SoundEffect eatghostSound;
private Game1 game1;
private int ghostType;
private Board board;
private Orientation orientation;
public Point position, targetPosition, origin;
int enemyLives = 4;
int patrolSize;
int patrolPosition = 0;
int direction = 1;
int frame = 0;
public static int ghostValue = 200;
Dictionary<Direction, Vector2> ghostColor;
Dictionary<Direction, Point> Surroundings;
Direction gDirection = Direction.Up;
#endregion
#region Constructor
public Ghost(Game1 game, int x, int y, int ghostType) : base(game)
{
orientation = Game1.rnd.Next(2) > 0 ? Orientation.Horizontal : Orientation.Vertical;
texture = game.SpriteSheet;
spriteBatch = game.SpriteBatch;
this.ghostType = ghostType;
position.Y = y;
position.X = x;
targetPosition = position;
game1 = game;
board = game1.Board;
origin = targetPosition = position;
patrolSize = 2 + Game1.rnd.Next(4);
eatghostSound = game1.Content.Load<SoundEffect>("pacman_eatghost");
Surroundings = new Dictionary<Direction, Point>
{
[Direction.Up] = new Point(0, -1),
[Direction.Down] = new Point(0, 1),
[Direction.Left] = new Point(-1, 0),
[Direction.Right] = new Point(0, 1),
};
ghostColor = new Dictionary<Direction, Vector2>
{
[Direction.Right] = new Vector2(0, ghostType),
[Direction.Left] = new Vector2(2, ghostType),
[Direction.Up] = new Vector2(4, ghostType),
[Direction.Down] = new Vector2(6, ghostType),
};
}
#endregion
#region Properties
public Board Board => board;
#endregion
#region Methods
public override void Update(GameTime gameTime)
{
Rectangle pRect = new Rectangle(game1.Player.position, new Point(Game1.outputTileSize));
Rectangle EnemyArea = new Rectangle(((position.ToVector2()) * Game1.outputTileSize).ToPoint(), new Point(Game1.outputTileSize));
ChasePattern(ghostType);
if (EnemyArea.Intersects(pRect))
{
Pellet.GetPelletStatus();
if (Pellet.powerPellet)
{
this.Die();
}
else
{
game1.Player.Die();
}
}
}
//Draws the different types of ghosts
public override void Draw(GameTime gameTime)
{
Rectangle outRect = new Rectangle(position.X * Game1.outputTileSize, position.Y * Game1.outputTileSize, Game1.outputTileSize, Game1.outputTileSize);
Rectangle sourceRec = new Rectangle(((ghostColor[gDirection] + Vector2.UnitX * frame) * 16).ToPoint(), new Point(15));
Rectangle sourcePelletRec = new Rectangle(8 * 16, 0, 16, 15);
spriteBatch.Begin();
Pellet.GetPelletStatus();
if (!Pellet.powerPellet)
{
spriteBatch.Draw(texture, outRect, sourceRec, Color.White);
}
else
{
spriteBatch.Draw(texture, outRect, sourcePelletRec, Color.White);
}
spriteBatch.End();
}
public void Die()
{
eatghostSound.Play();
enemyLives--;
int n = 4 - enemyLives;
AssignGhostValue(n);
game1.Ghosts.Remove(this);
game1.Components.Remove(this);
position = targetPosition = origin;
game1.Ghosts.Add(this);
game1.Components.Add(this);
}
public void AssignGhostValue(int n)
{
ghostValue = ghostValue * n;
game1.Player.Score += ghostValue;
}
public void ChasePattern(int ghostType)
{
int ghosType = ghostType;
int blinky = 0, pinky = 1, inky = 2, clyde = 3;
if (ghosType == blinky)
{
ChaseAggressive();
}
else if (ghosType == pinky)
{
ChaseAmbush();
}
else if (ghosType == inky)
{
ChasePatrol();
}
else if (ghosType == clyde)
{
ChaseRandom();
}
}
public void ChaseAggressive()
{
//Blinky the red ghost is very aggressive in its approach while chasing Pac - Man and will follow Pac-Man once located
float dist = Vector2.Distance(position.ToVector2(), targetPosition.ToVector2());
if (dist <= 1)
{
List<Direction> availableDirections = new List<Direction>();
foreach (var dir in Surroundings)
if (game1.Board.board[targetPosition.X / (Game1.outputTileSize) + dir.Value.X, targetPosition.Y / (Game1.outputTileSize) + dir.Value.Y] == ' ')
availableDirections.Add(dir.Key);
if (availableDirections.Count == 0) return;
availableDirections = availableDirections.OrderBy(dir =>
{
float distP1 = Vector2.Distance(targetPosition.ToVector2() + Surroundings[dir].ToVector2() * Game1.outputTileSize, game1.Player.position.ToVector2());
return distP1;
}).ToList();
direction = availableDirections[0];
direction = Surroundings[availableDirections.Count - 1];
targetPosition = targetPosition + availableDirections[direction]. Game1.outputTileSize;
}
else
{
//Position is not the same, move the guy
Vector2 vec = targetPosition.ToVector2() - position.ToVector2();
vec.Normalize();
position = (position.ToVector2() + vec).ToPoint();
//Incrementar frame
if ((position.X + position.Y) % 4 == 0)
frame++;
if (frame > 1) frame = -1;
}
}
}
}
In relation to the question asked here (How to place spheres in a half circle shape between 2 points) that generates spheres between two points A and B.
How do I create just one sphere that moves from Point A to Point B and then back from Point B to Point A in a loop cycle? How do I use Lerp in this context?
I have tried making the sphere move in the angle (half circle) described in the below code but it always moves in a straight line.
The below code generates spheres between two points.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GetCurves : MonoBehaviour
{
public GameObject A;
public GameObject B;
public int amount;
[ContextMenu("PlaceSpheres()")]
public void Start()
{
PlaceSpheres(A.transform.position, B.transform.position, amount);
}
public void PlaceSpheres(Vector3 posA, Vector3 posB, int numberOfObjects)
{
// get circle center and radius
var radius = Vector3.Distance(posA, posB) / 2f;
var centerPos = (posA + posB) / 2f;
// get a rotation that looks in the direction
// posA -> posB
var centerDirection = Quaternion.LookRotation((posB - posA).normalized);
for (var i = 0; i < numberOfObjects; i++)
{
var angle = Mathf.PI * (i+1) / (numberOfObjects + 1); //180 degrees
var x = Mathf.Sin(angle) * radius;
var z = Mathf.Cos(angle) * radius;
var pos = new Vector3(x, 0, z);
// Rotate the pos vector according to the centerDirection
pos = centerDirection * pos;
var sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
sphere.transform.position = centerPos + pos;
sphere.transform.localScale = new Vector3(0.05f, 0.05f, 0.05f);
}
}
}
The below script I had created that makes an object move between two points in a loop but only in a straight line. How do I make it move in a curve (180 degrees)?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RunInLoop : MonoBehaviour
{
public float speed = 0.25f;
public Transform PointA;
public Transform PointB;
private Vector3 origin;
private bool backToOrigin;
void Start()
{
transform.position = PointA.transform.position;
origin = transform.position;
}
void Update()
{
transform.position = Vector3.MoveTowards(transform.position, backToOrigin ? origin : PointB.transform.position, speed * Time.deltaTime);
// if one of the two positions is reached invert the flag
if (transform.position == PointB.transform.position || transform.position == origin)
{
backToOrigin = !backToOrigin;
}
}
}
Solution using your code
As I told you in my last answer that provided your first code you should store them in a list and then make the object move between them:
public class GetCurves : MonoBehaviour
{
public GameObject A;
public GameObject B;
public int amount;
public float moveSpeed;
private List<Vector3> positions = new List<Vector3>();
private Transform sphere;
private int currentIndex = 0;
private bool movingForward = true;
private void Start()
{
sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere).transform;
sphere.transform.localScale = new Vector3(0.05f, 0.05f, 0.05f);
GeneratePositions(A.transform.position, B.transform.position, amount);
sphere.position = positions[0];
}
private void GeneratePositions(Vector3 posA, Vector3 posB, int numberOfObjects)
{
// get circle center and radius
var radius = Vector3.Distance(posA, posB) / 2f;
var centerPos = (posA + posB) / 2f;
// get a rotation that looks in the direction
// posA -> posB
var centerDirection = Quaternion.LookRotation((posB - posA).normalized);
for (var i = 0; i < numberOfObjects; i++)
{
var angle = Mathf.PI * (i + 1) / (numberOfObjects + 1); //180 degrees
var x = Mathf.Sin(angle) * radius;
var z = Mathf.Cos(angle) * radius;
var pos = new Vector3(x, 0, z);
// Rotate the pos vector according to the centerDirection
pos = centerDirection * pos;
// store them in a list this time
positions.Add(centerPos + pos);
}
}
private void Update()
{
if (positions == null || positions.Count == 0) return;
// == for Vectors works with precision of 0.00001
// if you need a better precision instead use
//if(!Mathf.Approximately(Vector3.Distance(sphere.position, positions[currentIndex]), 0f))
if (sphere.position != positions[currentIndex])
{
sphere.position = Vector3.MoveTowards(sphere.transform.position, positions[currentIndex], moveSpeed * Time.deltaTime);
return;
}
// once the position is reached select the next index
if (movingForward)
{
if (currentIndex + 1 < positions.Count)
{
currentIndex++;
}
else if (currentIndex + 1 >= positions.Count)
{
currentIndex--;
movingForward = false;
}
}
else
{
if (currentIndex - 1 >= 0)
{
currentIndex--;
}
else
{
currentIndex++;
movingForward = true;
}
}
}
}
If you want to stick to Single-Responsibility-Principles you could also seperate the movement from the list generation like e.g.
public class GetCurves : MonoBehaviour
{
public GameObject A;
public GameObject B;
public int amount;
public float moveSpeed;
private void Start()
{
GeneratePositions(A.transform.position, B.transform.position, amount);
}
private void GeneratePositions(Vector3 posA, Vector3 posB, int numberOfObjects)
{
// get circle center and radius
var radius = Vector3.Distance(posA, posB) / 2f;
var centerPos = (posA + posB) / 2f;
// get a rotation that looks in the direction
// posA -> posB
var centerDirection = Quaternion.LookRotation((posB - posA).normalized);
List<Vector3> positions = new List<Vector3>();
for (var i = 0; i < numberOfObjects; i++)
{
var angle = Mathf.PI * (i + 1) / (numberOfObjects + 1); //180 degrees
var x = Mathf.Sin(angle) * radius;
var z = Mathf.Cos(angle) * radius;
var pos = new Vector3(x, 0, z);
// Rotate the pos vector according to the centerDirection
pos = centerDirection * pos;
// store them in a list this time
positions.Add(centerPos + pos);
}
var sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
sphere.transform.localScale = new Vector3(0.05f, 0.05f, 0.05f);
var movement = sphere.AddComponent<MoveBetweenPoints>();
movement.positions = positions;
movement.moveSpeed = moveSpeed;
}
and in a seperate script
public class MoveBetweenPoints : MonoBehaviour
{
public List<Vector3> positions = new List<Vector3>();
public float moveSpeed;
privtae bool movingForward = true;
private int currentIndex = 0;
private void Update()
{
if (positions == null || positions.Count == 0) return;
// == for Vectors works with precision of 0.00001
// if you need a better precision instead use
//if(!Mathf.Approximately(Vector3.Distance(sphere.position, positions[currentIndex]), 0f))
if (sphere.position != positions[currentIndex])
{
transform.position = Vector3.MoveTowards(transform.position, positions[currentIndex], moveSpeed * Time.deltaTime);
return;
}
// once the position is reached select the next index
if (movingForward)
{
if (currentIndex + 1 < positions.Count)
{
currentIndex++;
}
else if (currentIndex + 1 >= positions.Count)
{
currentIndex--;
movingForward = false;
}
}
else
{
if (currentIndex - 1 >= 0)
{
currentIndex--;
}
else
{
currentIndex++;
movingForward = true;
}
}
}
}
Actual Solution
However, if you want a smooth movement on a circle curve ... why even reduce that circle curcve to a certain amount of positions? You could directly moove according to the angle between 0° and 180° like this:
public class GetCurves : MonoBehaviour
{
public GameObject A;
public GameObject B;
// now in Angles per second
public float moveSpeed;
private Transform sphere;
private bool movingForward = true;
private float angle;
private void Start()
{
sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere).transform;
sphere.transform.localScale = new Vector3(0.05f, 0.05f, 0.05f);
}
private void Update()
{
if (movingForward)
{
angle += moveSpeed * Time.deltaTime;
}
else
{
angle -= moveSpeed * Time.deltaTime;
}
if (angle < 0)
{
angle = 0;
movingForward = true;
}
else if (angle > 180)
{
angle = 180;
movingForward = false;
}
// get circle center and radius
var radius = Vector3.Distance(A.transform.position, B.transform.position) / 2f;
var centerPos = (A.transform.position + B.transform.position) / 2f;
// get a rotation that looks in the direction
// posA -> posB
var centerDirection = Quaternion.LookRotation((B.transform.position - A.transform.position).normalized);
var x = Mathf.Sin(angle * Mathf.Deg2Rad) * radius;
var z = Mathf.Cos(angle * Mathf.Deg2Rad) * radius;
var pos = new Vector3(x, 0, z);
// Rotate the pos vector according to the centerDirection
pos = centerDirection * pos;
sphere.position = centerPos + pos;
}
}
private void MoveToNewFormation()
{
squadMembers = GameObject.FindGameObjectsWithTag("Squad Member");
float step = speed * Time.deltaTime;
for (int i = 0; i < squadMembers.Length; i++)
{
squadMembers[i].transform.LookAt(newpos[i]);
squadMembers[i].transform.position = Vector3.MoveTowards(squadMembers[i].transform.position, newpos[i], step);
//squadMembers[i].transform.rotation = qua[i];
}
}
And calling it in the Update:
void Update()
{
if (Input.GetKeyDown(KeyCode.F))
{
ChangeFormation();
}
if (move == true)
MoveToNewFormation();
}
Once when one of the squadMembers reached to the newpos then i want to make
squadMembers[i].transform.rotation = qua[i];
qua is a List and i want to rotate the squad member once he reached the newpos.
Inside MoveToNewFormation i thought to add after the loop the line:
if (squadMembers[i].transform.position == newpos[i])
{
squadMembers[i].transform.rotation = qua[i];
}
But it's after the loop so 'i' not exist.
This is the complete script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SquadFormation : MonoBehaviour
{
enum Formation
{
Square, Circle, Triangle
}
public Transform squadMemeber;
public int columns = 4;
public int squareSpace = 10;
public int circleSpace = 40;
public int numberOfObjects = 20;
public float yOffset = 0;
public float speed = 3;
private Formation formation;
private GameObject[] squadMembers;
private List<Quaternion> qua = new List<Quaternion>();
private List<Vector3> newpos = new List<Vector3>();
private bool move = false;
// Use this for initialization
void Start()
{
formation = Formation.Square;
ChangeFormation();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.F))
{
ChangeFormation();
}
if (move == true)
MoveToNewFormation();
}
private void ChangeFormation()
{
switch (formation)
{
case Formation.Square:
FormationSquare();
break;
case Formation.Circle:
FormationCircle();
break;
}
}
private Vector3 FormationSquarePositionCalculation(int index) // call this func for all your objects
{
float posX = (index % columns) * squareSpace;
float posY = (index / columns) * squareSpace;
return new Vector3(posX, posY);
}
private void FormationSquare()
{
for (int i = 0; i < numberOfObjects; i++)
{
Transform go = Instantiate(squadMemeber);
Vector3 pos = FormationSquarePositionCalculation(i);
go.position = new Vector3(transform.position.x + pos.x, 0, transform.position.y + pos.y);
go.Rotate(new Vector3(0, -90, 0));
go.tag = "Squad Member";
}
formation = Formation.Circle;
}
private Vector3 FormationCirclePositionCalculation(Vector3 center, float radius, int index, float angleIncrement)
{
float ang = index * angleIncrement;
Vector3 pos;
pos.x = center.x + radius * Mathf.Sin(ang * Mathf.Deg2Rad);
pos.z = center.z + radius * Mathf.Cos(ang * Mathf.Deg2Rad);
pos.y = center.y;
return pos;
}
private void FormationCircle()
{
Vector3 center = transform.position;
float radius = (float)circleSpace / 2;
float angleIncrement = 360 / (float)numberOfObjects;
for (int i = 0; i < numberOfObjects; i++)
{
Vector3 pos = FormationCirclePositionCalculation(center, radius, i, angleIncrement);
var rot = Quaternion.LookRotation(center - pos);
pos.y = Terrain.activeTerrain.SampleHeight(pos);
pos.y = pos.y + yOffset;
newpos.Add(pos);
qua.Add(rot);
}
move = true;
formation = Formation.Square;
}
private void MoveToNewFormation()
{
squadMembers = GameObject.FindGameObjectsWithTag("Squad Member");
float step = speed * Time.deltaTime;
for (int i = 0; i < squadMembers.Length; i++)
{
squadMembers[i].transform.LookAt(newpos[i]);
squadMembers[i].transform.position = Vector3.MoveTowards(squadMembers[i].transform.position, newpos[i], step);
//squadMembers[i].transform.rotation = qua[i];
}
//if (squadMembers[i].transform.position == newpos[i])
}
}
You can use a threshold and check the distance using that threshold.
Define threshold like this at start of script.
public float threshold = 0.1f;
Then change the MoveToNewFormation() function like this:
private void MoveToNewFormation()
{
squadMembers = GameObject.FindGameObjectsWithTag("Squad Member");
float step = speed * Time.deltaTime;
for (int i = 0; i < squadMembers.Length; i++)
{
squadMembers[i].transform.LookAt(newpos[i]);
squadMembers[i].transform.position =
Vector3.MoveTowards(squadMembers[i].transform.position, newpos[i], step);
if(Vector3.Distance(squadMembers[i].transform.position,newpos[i])<threshold){
squadMembers[i].transform.rotation = qua[i];
}
}
//if (squadMembers[i].transform.position == newpos[i])
}
When it's square formation i can set the space fine.
But i'm not sure how to do it with the circle formation.
Inside the FormationSquare method i'm using the space variable for the square formation. Now i need to do the same idea for the circle formation too.
Maybe inside the RandomCircle to change something and using the space variable ?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SquadFormation : MonoBehaviour
{
enum Formation
{
Square, Circle
}
public Transform squadMemeber;
public int columns = 4;
public int space = 10;
public int numObjects = 20;
public float yOffset = 1;
private Formation formation;
// Use this for initialization
void Start()
{
formation = Formation.Square;
ChangeFormation();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.F))
{
GameObject[] objects = GameObject.FindGameObjectsWithTag("Squad Member");
if (objects.Length > 0)
{
foreach (GameObject obj in objects)
Destroy(obj);
}
ChangeFormation();
}
}
private void ChangeFormation()
{
switch (formation)
{
case Formation.Square:
for (int i = 0; i < 23; i++)
{
Transform go = Instantiate(squadMemeber);
Vector3 pos = FormationSquare(i);
go.position = new Vector3(transform.position.x + pos.x, 0, transform.position.y + pos.y);
go.Rotate(new Vector3(0, -90, 0));
go.tag = "Squad Member";
}
formation = Formation.Circle;
break;
case Formation.Circle:
Vector3 center = transform.position;
for (int i = 0; i < numObjects; i++)
{
Vector3 pos = RandomCircle(center, 5.0f);
var rot = Quaternion.LookRotation(center - pos);
pos.y = Terrain.activeTerrain.SampleHeight(pos);
pos.y = pos.y + yOffset;
Transform insObj = Instantiate(squadMemeber, pos, rot);
insObj.rotation = rot;
insObj.tag = "Squad Member";
}
formation = Formation.Square;
break;
}
}
Vector2 FormationSquare(int index) // call this func for all your objects
{
float posX = (index % columns) * space;
float posY = (index / columns) * space;
return new Vector2(posX, posY);
}
Vector3 RandomCircle(Vector3 center, float radius)
{
float ang = Random.value * 360;
Vector3 pos;
pos.x = center.x + radius * Mathf.Sin(ang * Mathf.Deg2Rad);
pos.z = center.z + radius * Mathf.Cos(ang * Mathf.Deg2Rad);
pos.y = center.y;
return pos;
}
}
The issue here is that your RandomCircle() method is...well, random. You're just arbitrarily grabbing an angle around the circle, without any regard for where other squad members have been placed, meaning they'll practically never be evenly distributed.
Consider calculating the angle that will separate each squad member (if distributed evenly) beforehand, then perform a similar approach to FormationSquare() where you iterate through the squad to distribute them.
This may be a bit closer to what you want (basing this on the assumption that RandomCircle() already works as designed):
Vector3 FormationCircle(Vector3 center, float radius, int index, float angleIncrement)
{
float ang = index * angleIncrement;
Vector3 pos;
pos.x = center.x + radius * Mathf.Sin(ang * Mathf.Deg2Rad);
pos.z = center.z + radius * Mathf.Cos(ang * Mathf.Deg2Rad);
pos.y = center.y;
return pos;
}
To call it, you'd do:
Vector3 center = transform.position;
float radius = (float)space / 2;
float angleIncrement = 360 / (float)numObjects;
for (int i = 0; i < numObjects; i++)
{
Vector3 pos = FormationCircle(center, radius, i, angleIncrement);
// ...
}
Hope this helps! Let me know if you have any questions.
When I press left or up arrow keys the sprite gets out of the window/screen. My code:
Texture2D m_PlayerShipTex;
Rectangle m_PlayerShipHitBox;
Vector2 m_PlayerShipPos = new Vector2(400, 486);
Vector2 m_PlayerShipOrigin;
int m_PlayerShipCurrentFrame = 1;
int m_PlayerShipFrameWidth = 62;
int m_PlayerShipFrameHeight = 64;
float m_Timer = 0f;
float m_Interval = 100;
public void LoadContent(ContentManager Content)
{
m_PlayerShipTex = Content.Load<Texture2D>(".\\gameGraphics\\gameSprites\\playerShip\\playerShipSpriteSheet");
}
public void Update(GameTime gameTime)
{
m_PlayerShipHitBox = new Rectangle(m_PlayerShipCurrentFrame * m_PlayerShipFrameWidth, 0, m_PlayerShipFrameWidth, m_PlayerShipFrameHeight);
m_PlayerShipOrigin = new Vector2(m_PlayerShipHitBox.X / 2, m_PlayerShipHitBox.Y / 2);
MouseState m_MouseState = Mouse.GetState();
KeyboardState m_KeyboardState = Keyboard.GetState();
m_Timer += (float)gameTime.ElapsedGameTime.Milliseconds;
if (m_Timer > m_Interval)
{
m_PlayerShipCurrentFrame++;
m_Timer = 0f;
}
if (m_PlayerShipCurrentFrame == 2)
{
m_PlayerShipCurrentFrame = 0;
}
m_PlayerShipHitBox = new Rectangle(m_PlayerShipCurrentFrame * m_PlayerShipFrameWidth, 0, m_PlayerShipFrameWidth, m_PlayerShipFrameHeight);
m_PlayerShipOrigin = new Vector2(m_PlayerShipHitBox.Width / 2, m_PlayerShipHitBox.Height / 2);
if (m_KeyboardState.IsKeyDown(Keys.Right))
{
m_PlayerShipPos.X += 3;
}
if (m_KeyboardState.IsKeyDown(Keys.Left))
{
m_PlayerShipPos.X -= 3;
}
if (m_KeyboardState.IsKeyDown(Keys.Down))
{
m_PlayerShipPos.Y += 3;
}
if (m_KeyboardState.IsKeyDown(Keys.Up))
{
m_PlayerShipPos.Y -= 3;
}
if (m_PlayerShipPos.X <= 0)
{
m_PlayerShipPos.X = 0;
}
if (m_PlayerShipPos.X + m_PlayerShipTex.Width >= 1141)
{
m_PlayerShipPos.X = 1141 - m_PlayerShipTex.Width;
}
if (m_PlayerShipPos.Y <= 0)
{
m_PlayerShipPos.Y = 0;
}
if (m_PlayerShipPos.Y + m_PlayerShipTex.Height >= 620)
{
m_PlayerShipPos.Y = 620 - m_PlayerShipTex.Height;
}
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(m_PlayerShipTex, m_PlayerShipPos, m_PlayerShipHitBox, Color.White, 0f, m_PlayerShipOrigin, 1.0f, SpriteEffects.None, 0);
}
I don't know what could be wrong, my window is 800x600 but if I set m_PlayerShipTex.Width >= 800 I can get only to half of the screen, that's why I'm using 1141. Same goes for window height... What am I doing wrong and why the ship's out of the "reacheable" area?
To fix the original problem, use this draw function:
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(m_PlayerShipTex, m_PlayerShipPos, m_PlayerShipHitBox, Color.White, 0f, Vector2.Zero, 1.0f, SpriteEffects.None, 0);
}
This will use (0,0) as the origin for drawing; which means that your "edge" calculations will work as originally expected. If you want the centered origin, then you need to account for that adjustment when calculating the edges.
The only reason to change the origin is to make rotation easier; in general, you can just use Vector2.Zero.