Collision Detection in C# XNA - c#

Collision detection has been a huge issue for me lately, been breaking my mind over this particular problem.
After I got a reasonable collision detection for my Super Mario World remake in C# (XNA) I have the following problem: I keep getting sort of stuck in blocks when I jump against them...
Example: https://gyazo.com/0f1ac6f4894f41aa4bcbdc73e572e36d
This is my current code than handles the collision: http://pastebin.com/iWsnffWQ
If anyone knows anything that could help my problem, I have been searching high and low for the solution but I to no avail...
EDIT:
This problem has been fixed though a new one arised with object collision on the infamous mario "Mystery Blocks". Whenever I stand on them (not moving) either mario or the world starts to vibrate up and down by about one pixel.
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace PlatFormer
{
public abstract class Entity
{
protected ContentManager _Content;
protected Texture2D _Image;
protected Texture2D _Outline;
protected SpriteSheetAnimation _MoveAnimation;
protected FileManager _FileManager;
protected List<List<string>> _Attributes;
protected List<List<string>> _Contents;
protected Vector2 _Velocity;
protected Vector2 _PrevPosition;
protected Vector2 _Frames;
protected Rectangle _Collbox;
private Rectangle _TileBounds;
protected int _Health;
protected float _MoveSpeed;
protected float _Gravity;
protected float _PreviousBottom;
protected bool _ActivateGravity;
protected bool _TilePositionSync;
protected bool _FacingRight;
protected const float _Friction = 0.9f;
protected const float _Grav = 10f;
protected const float _TerminalVelocity = 10f;
protected Vector2 _Acceleration;
public bool _OnGround;
protected bool _IsJumping;
protected int collisiondeny;
public Vector2 Position;
public SpriteSheetAnimation Animation
{
get { return _MoveAnimation; }
}
public virtual void LoadContent(ContentManager content)
{
_Content = new ContentManager(content.ServiceProvider, "Content");
_Attributes = new List<List<string>>();
_Contents = new List<List<string>>();
}
public virtual void LoadContent(ContentManager content, InputManager input)
{
_Content = new ContentManager(content.ServiceProvider, "Content");
_Attributes = new List<List<string>>();
_Contents = new List<List<string>>();
}
public virtual void UnloadContent()
{
_Content.Unload();
}
public virtual void Update(GameTime gameTime, List<List<WorldTile>> TileMap, List<Enemy> EntList)
{
_PrevPosition = Position;
Position.X = _FacingRight ? Position.X + _MoveSpeed : Position.X - _MoveSpeed;
_Velocity.Y += _Gravity;
if (!_OnGround) { }
else
_Velocity.Y = 0;
UpdatePhysics(gameTime, TileMap, EntList);
_MoveAnimation.Position = Position;
_MoveAnimation.Update(gameTime);
}
public virtual void Update(GameTime gameTime, InputManager input, List<List<WorldTile>> TileMap)
{
}
public virtual void Draw(SpriteBatch spriteBatch)
{
_MoveAnimation.Draw(spriteBatch);
}
protected virtual void UpdatePhysics(GameTime gameTime, List<List<WorldTile>> TileMap, List<Enemy> EntList)
{
_Acceleration *= _Friction;
_Velocity *= _Friction;
_Velocity += _Acceleration;
Position.X = _FacingRight ? Position.X + _Velocity.X : Position.X - _Velocity.X;
Position.Y += _Velocity.Y;
if (Math.Abs(_Acceleration.X) < 0.001f)
{
_MoveAnimation.IsActive = false;
}
UpdateCollBox();
CollisionHandle(TileMap);
EntCollisionHandle(EntList);
if (Position.X == _PrevPosition.X)
_Velocity.X = 0;
if (Position.Y == _PrevPosition.Y)
_Velocity.Y = 0;
}
protected virtual void UpdatePhysics(GameTime gameTime, InputManager input, List<List<WorldTile>> TileMap)
{
float totalSecElapsed = gameTime.ElapsedGameTime.Milliseconds / 1000f;
_Acceleration.X *= _Friction;
_Velocity.X *= _Friction;
_Acceleration.Y = _Grav;
_Velocity.Y += _Acceleration.Y * totalSecElapsed;
_Velocity.X += _Acceleration.X;
if (_Velocity.Y >= _TerminalVelocity)
{
_Velocity.Y = _TerminalVelocity;
}
Position += _Velocity;
if (Math.Abs(_Acceleration.X) < 0.001f)
{
_MoveAnimation.IsActive = false;
}
UpdateCollBox();
CollisionHandle(TileMap); //replace with horizontal collision first then vertical collision
//TestCollisionHandle(TileMap);
if (Position.X == _PrevPosition.X)
_Velocity.X = 0;
if (Position.Y == _PrevPosition.Y)
_Velocity.Y = 0;
}
public void ObjectCollision(List<LevelObject> obj)
{
//OnThisNiceMysteryBox = false;
for (int i = 0; i < obj.Count; i++)
{
if (_Collbox.Intersects(obj[i].Bounds))
{
if (obj[i].Collision != TileCollision.Empty)
{
Vector2 depth = IntersectDepth(_Collbox, obj[i].Bounds);
if (depth != Vector2.Zero)
{
float absDepthX = Math.Abs(depth.X);
float absDepthY = Math.Abs(depth.Y);
if (absDepthY < absDepthX)
{
if (_Collbox.Top <= obj[i].Bounds.Bottom && _Collbox.Top >= obj[i].Bounds.Top)
{
Vector2 tempPos = obj[i].Position;
if (obj[i] is MysteryBox)
{
obj.Remove(obj[i]);
obj.Insert(i, new MysteryBox(tempPos));
}
}
if (_PreviousBottom <= obj[i].Bounds.Top)
{
_OnGround = true;
}
if (obj[i].Collision == TileCollision.Solid || _OnGround)
{
Position = new Vector2((float)Math.Round(Position.X), (float)Math.Round(Position.Y + depth.Y));
_Velocity.Y = 0;
UpdateCollBox();
}
}
else if (obj[i].Collision == TileCollision.Solid)
{
Position = new Vector2((float)Math.Round(Position.X + depth.X), (float)Math.Round(Position.Y));
UpdateCollBox();
}
}
}
}
_PreviousBottom = _Collbox.Bottom;
}
}
protected void EntCollisionHandle(List<Enemy> EntList)
{
for (int i = 0; i < EntList.Count; i++)
{
if (!(EntList[i] == this))
{
Vector2 intersection = IntersectDepth(this._Collbox, EntList[i]._Collbox);
if (intersection != Vector2.Zero)
{
if (collisiondeny == 0)
{
_FacingRight = !_FacingRight;
Position.X = _FacingRight ? Position.X - intersection.X : Position.X + intersection.X;
collisiondeny = 1;
}
else
{
collisiondeny--;
}
//if intersection has occured call both collision handles in colliding classes
}
}
}
}
protected void CollisionHandle(List<List<WorldTile>> TileMap)
{
int leftTile = (int)Math.Floor((float)_Collbox.Left / WorldTile.Width);
int rightTile = (int)Math.Ceiling(((float)_Collbox.Right / WorldTile.Width)) - 1;
int topTile = (int)Math.Floor((float)_Collbox.Top / WorldTile.Height);
int bottomTile = (int)Math.Ceiling(((float)_Collbox.Bottom / WorldTile.Height)) - 1;
_OnGround = false;
for (int y = topTile; y <= bottomTile; y++)
{
for (int x = leftTile; x <= rightTile; x++)
{
TileCollision collision = TileCollision.Empty;
if (y >= 0)
{
if (x >= 0)
{
if (y < TileMap.Count && x < TileMap[y].Count)
collision = TileMap[y][x].Collision;
}
else
{
collision = TileCollision.Solid;
}
}
if (collision != TileCollision.Empty)
{
_TileBounds = new Rectangle(x * WorldTile.Width, y * WorldTile.Height, WorldTile.Width, WorldTile.Height);
Vector2 depth = IntersectDepth(_Collbox, _TileBounds);
if (depth != Vector2.Zero)
{
float absDepthX = Math.Abs(depth.X);
float absDepthY = Math.Abs(depth.Y);
if (absDepthY <= absDepthX || collision == TileCollision.OneWay)
{
if (_PreviousBottom <= _TileBounds.Top)
_OnGround = true;
if ((collision == TileCollision.Solid) || _OnGround)
{
Position = new Vector2((int)Math.Round(Position.X), (int)Math.Round(Position.Y + depth.Y));
UpdateCollBox();
}
}
else if (collision == TileCollision.Solid)
{
Position = new Vector2((int)Math.Round(Position.X + depth.X), (int)Math.Round(Position.Y));
_FacingRight = !_FacingRight;
//_Velocity.Y = 0;
UpdateCollBox();
}
}
}
}
}
_PreviousBottom = _Collbox.Bottom;
}
protected void TestCollisionHandle(List<List<WorldTile>> TileMap)
{
int leftTile = (int)Math.Floor((float)_Collbox.Left / WorldTile.Width);
int rightTile = (int)Math.Ceiling(((float)_Collbox.Right / WorldTile.Width)) - 1;
int topTile = (int)Math.Floor((float)_Collbox.Top / WorldTile.Height);
int bottomTile = (int)Math.Ceiling(((float)_Collbox.Bottom / WorldTile.Height)) - 1;
_OnGround = false;
for (int y = topTile; y <= bottomTile; y++)
{
for (int x = leftTile; x <= rightTile; x++)
{
TileCollision collision = TileCollision.Empty;
if (y >= 0)
{
if (x >= 0)
{
if (y < TileMap.Count && x < TileMap[y].Count)
collision = TileMap[y][x].Collision;
}
}
if(collision != TileCollision.Empty)
{
//if collision can occor, get tilecollisionbox for horizontal
_TileBounds = new Rectangle(x * WorldTile.Width, y * WorldTile.Height, WorldTile.Width, WorldTile.Height);
//get the horizontal collision depth, will return zero if none is found
GetHorizontalIntersectionDepth(_Collbox, _TileBounds);
}
}
}
_PreviousBottom = _Collbox.Bottom;
}
private void UpdateCollBox()
{
_Collbox = new Rectangle((int)Math.Round(Position.X), (int)Math.Round(Position.Y), Animation.FrameWidth, Animation.FrameHeight);
}
private Vector2 IntersectDepth(Rectangle rectangleA, Rectangle rectangleB)
{
float halfWidthA = rectangleA.Width / 2.0f;
float halfHeightA = rectangleA.Height / 2.0f;
float halfWidthB = rectangleB.Width / 2.0f;
float halfHeightB = rectangleB.Height / 2.0f;
Vector2 centerA = new Vector2(rectangleA.Left + halfWidthA, rectangleA.Top + halfHeightA);
Vector2 centerB = new Vector2(rectangleB.Left + halfWidthB, rectangleB.Top + halfHeightB);
float distanceX = centerA.X - centerB.X;
float distanceY = centerA.Y - centerB.Y;
float minDistanceX = halfWidthA + halfWidthB;
float minDistanceY = halfHeightA + halfHeightB;
// If no intersection is happening, return Vector2.Zero
if (Math.Abs(distanceX) >= minDistanceX || Math.Abs(distanceY) >= minDistanceY)
return Vector2.Zero;
// Calculate instersection depth
float depthX = distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
float depthY = distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY;
return new Vector2(depthX, depthY);
}
private float GetHorizontalIntersectionDepth(Rectangle rectA, Rectangle rectB)
{
// Calculate half sizes.
float halfWidthA = rectA.Width / 2.0f;
float halfWidthB = rectB.Width / 2.0f;
// Calculate centers.
float centerA = rectA.Left + halfWidthA;
float centerB = rectB.Left + halfWidthB;
// Calculate current and minimum-non-intersecting distances between centers.
float distanceX = centerA - centerB;
float minDistanceX = halfWidthA + halfWidthB;
// If we are not intersecting at all, return (0, 0).
if (Math.Abs(distanceX) >= minDistanceX)
return 0f;
// Calculate and return intersection depths.
return distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
}
private float GetVerticalIntersectionDepth(Rectangle rectA, Rectangle rectB)
{
// Calculate half sizes.
float halfHeightA = rectA.Height / 2.0f;
float halfHeightB = rectB.Height / 2.0f;
// Calculate centers.
float centerA = rectA.Top + halfHeightA;
float centerB = rectB.Top + halfHeightB;
// Calculate current and minimum-non-intersecting distances between centers.
float distanceY = centerA - centerB;
float minDistanceY = halfHeightA + halfHeightB;
// If we are not intersecting at all, return (0, 0).
if (Math.Abs(distanceY) >= minDistanceY)
return 0f;
// Calculate and return intersection depths.
return distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY;
}
public enum Direction
{
Horizontal,
Vertical
}
private bool TileIntersectsPlayer(Rectangle player, Rectangle block, Direction direction, out Vector2 depth)
{
depth = direction == Direction.Vertical ? new Vector2(0, GetVerticalIntersectionDepth(player, block)) : new Vector2(GetHorizontalIntersectionDepth(player, block), 0);
return depth.Y != 0 || depth.X != 0;
}
}
}

Consider using or just compare your code to the libraries that exist already: see GeoLib which is very simple to use and/or clipper lib. 'Do not reinvent...'

Related

Player stuck in place when playing animation

I am using Sebastian Graves' Dark Souls in Unity series in order to make a game with souls-like mechanics and reached episode 4 but in comparison to his video, my player is tuck in place when using rolling or backstepping.
The problem seems to be coming from the AnimatorHandler script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Game
{
public class AnimatorHandler : MonoBehaviour
{
public Animator anim;
public InputHandler inputHandler;
public PlayerLocomotion playerLocomotion;
int vertical;
int horizontal;
public bool canRotate;
public void Initialize()
{
anim = GetComponent<Animator>();
inputHandler = GetComponentInParent<InputHandler>();
playerLocomotion = GetComponentInParent<PlayerLocomotion>();
vertical = Animator.StringToHash("Vertical");
horizontal = Animator.StringToHash("Horizontal");
}
public void UpdateAnimatorValues(float verticalMovement, float horizontalMovement)
{
float v = 0;
if (verticalMovement > 0 && verticalMovement < 0.55f)
{
v = 0.5f;
}
else if (verticalMovement > 0.55f)
{
v = 1;
}
else if (verticalMovement < 0 && verticalMovement > -0.55f)
{
v = -0.5f;
}
else if (verticalMovement < -0.55f)
{
v = -1;
}
else
{
v = 0;
}
float h = 0;
if (horizontalMovement > 0 && horizontalMovement < 0.55f)
{
h = 0.5f;
}
else if (horizontalMovement > 0.55f)
{
h = 1;
}
else if (horizontalMovement < 0 && horizontalMovement > -0.55f)
{
h = -0.5f;
}
else if (horizontalMovement < -0.55f)
{
h = -1;
}
else
{
h = 0;
}
anim.SetFloat(vertical, v, 0.1f, Time.deltaTime);
anim.SetFloat(horizontal, h, 0.1f, Time.deltaTime);
}
public void PlayTargetAnimation(string targetAnim, bool isInteracting)
{
anim.applyRootMotion = isInteracting;
anim.SetBool("isInteracting", isInteracting);
anim.CrossFade(targetAnim, 0.2f);
}
public void CanRotate()
{
canRotate = true;
}
public void StopRotation()
{
canRotate = false;
}
private void OnAnimatorMove()
{
if (inputHandler.isInteracting == false)
return;
float delta = Time.deltaTime;
playerLocomotion.rigidbody.drag = 0;
Vector3 deltaPosition = anim.deltaPosition;
deltaPosition.y = 0;
Vector3 velocity = deltaPosition / delta;
playerLocomotion.rigidbody.velocity = velocity;
// ???
}
}
}
The only method I found to make the player able to move was to delete playerLocomotion.rigidbody.velocity = velocity;
, but this generates another problem, as I am now able to change roll direction mid-animation.
How can I make this work?

The npc will move to the first or second point, then stop

The enemy will pick 1 or 2 positions, and then stop moving. If I get close enough, it will change to the chase state and follow me. So I do not know what causes them to freeze.
This holds the state machine, I intend to have more states and interactions, but I wanted to test the basic functionality, and it is broken.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BaseAI : MonoBehaviour
{
private enum State
{
Roaming,
ChaseTarget,
}
private PathfindAI pathMovement;
private Vector3 startingPosition;
public Vector3 roamPosition;
public PlayerScript player;
public Vector3 randomDirection;
[SerializeField] private State state;
public Vector3 playerPos;
private void Awake()
{
// pathMovement = GetComponent<PathfindAI>();
pathMovement = FindObjectOfType<PathfindAI>();
player = FindObjectOfType<PlayerScript>();
state = State.Roaming;
}
private void Start()
{
startingPosition = transform.position;
roamPosition = GetRoamingPos();
}
private void Update()
{
playerPos = player.PlayerPos();
switch (state)
{
default:
case State.Roaming:
pathMovement.MoveTo(roamPosition);
float reachedPos = 10f;
if (Vector3.Distance(transform.position, roamPosition) < reachedPos)
{
//reached destination
roamPosition = GetRoamingPos();
}
FindTarget();
break;
case State.ChaseTarget:
pathMovement.MoveTo(playerPos);
float attackRange = 10f;
if (Vector3.Distance(transform.position, playerPos) < attackRange)
{
//target within striking distance
}
break;
}
}
private Vector3 GetRoamingPos()
{
randomDirection = new Vector3(Random.Range(-1f, 1f), Random.Range(-1f, 1f), transform.position.z).normalized;
return startingPosition + randomDirection * Random.Range(10f, 70f);
}
private void FindTarget()
{
float targetRange = 50f;
if (Vector3.Distance(transform.position, playerPos) < targetRange)
{
state = State.ChaseTarget;
}
}
}
This allows them to move on the path from the pathfinding script. It uses A-star and I used a few tutorials to write it, mostly from CodeMonkey's youtube channel.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PathfindAI : MonoBehaviour
{
[SerializeField] float speed = 5f;
private int currentPathIndex;
private List<Vector3> pathVectorList;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Debug.Log(currentPathIndex);
}
public Vector3 GetPosition()
{
return transform.position;
}
public void MoveTo(Vector3 targetPosition)
{
SetTargetPos(targetPosition);
HandleMove();
}
private void SetTargetPos(Vector3 targetPosition)
{
currentPathIndex = 0;
pathVectorList = AStar.Instance.FindPathVector3(GetPosition(), targetPosition);
if (pathVectorList != null && pathVectorList.Count > 1)
{
pathVectorList.RemoveAt(0);
}
}
public void HandleMove()
{
if (pathVectorList != null)
{
Vector3 targetPosition = pathVectorList[currentPathIndex];
if(Vector3.Distance(transform.position, targetPosition) > 5f)
{
Vector3 moveDir = (targetPosition - transform.position).normalized;
float distanceBefore = Vector3.Distance(transform.position, targetPosition);
transform.position = transform.position + moveDir * speed * Time.deltaTime;
}
else
{
currentPathIndex++;
if(currentPathIndex >= pathVectorList.Count)
{
StopMoving();
}
}
}
}
private void StopMoving()
{
pathVectorList = null;
}
}
I suspect the error involves the HandleMove function. When I change where and how I call it; I can get it to break completely. It may be me setting the pathVectorList to null; however, it should be set back to a valid value on the next update when GetRoamingPos is called again within the roaming state.
when I go into the inspector and manually move the npc, it will find its way back to the position it chose. And if I move the player close enough it will chase me.
This is my A-Star Implementation
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AStar
{
private const int MOVE_STRAIGHT_COST = 10;
private const int MOVE_ANGLE_COST = 14;
public static AStar Instance { get; private set; }
private PathingGrid<PathNode> grid;
private List<PathNode> openList;
private List<PathNode> closedList;
public AStar(int width, int height)
{
Instance = this;
grid = new PathingGrid<PathNode>(width, height, 10f, Vector3.zero, (PathingGrid<PathNode> g, int x, int y) => new PathNode(g, x, y));
}
public PathingGrid<PathNode> GetGrid()
{
return grid;
}
public List<PathNode> FindPath(int startX, int startY, int endX, int endY)
{
PathNode startNode = grid.GetGridObject(startX, startY);
PathNode endNode = grid.GetGridObject(endX, endY);
openList = new List<PathNode> { startNode };
closedList = new List<PathNode>();
for (int x = 0; x<grid.GetWidth(); x++)
{
for (int y = 0; y<grid.GetHeight(); y++)
{
PathNode pathNode = grid.GetGridObject(x, y);
pathNode.gCost = int.MaxValue;
pathNode.CalcFCost();
pathNode.cameFromNode = null;
}
}
startNode.gCost = 0;
startNode.hCost = CalculateDistanceCost(startNode, endNode);
startNode.CalcFCost();
while (openList.Count > 0)
{
PathNode currentNode = GetLowestFCost(openList);
if (currentNode == endNode)
{
//reached final node
return CalculatedPath(endNode);
}
openList.Remove(currentNode);
closedList.Add(currentNode);
foreach (PathNode neighbourNode in GetNeighboursList(currentNode))
{
if (closedList.Contains(neighbourNode))
{
continue;
}
if (!neighbourNode.isWalkable)
{
closedList.Add(neighbourNode);
continue;
}
int tentativeGCost = currentNode.gCost + CalculateDistanceCost(currentNode, neighbourNode);
if (tentativeGCost < neighbourNode.gCost)
{
neighbourNode.cameFromNode = currentNode;
neighbourNode.gCost = tentativeGCost;
neighbourNode.hCost = CalculateDistanceCost(neighbourNode, endNode);
neighbourNode.CalcFCost();
if(!openList.Contains(neighbourNode))
{
openList.Add(neighbourNode);
}
}
}
}
//out of nodes on openList
return null;
}
private List<PathNode> GetNeighboursList(PathNode currentNode)
{
List<PathNode> neighbourList = new List<PathNode>();
if (currentNode.x - 1 >= 0)
{
//left
neighbourList.Add(GetNode(currentNode.x - 1, currentNode.y));
//left down
if (currentNode.y - 1 >= 0)
neighbourList.Add(GetNode(currentNode.x - 1, currentNode.y - 1));
//left up
if (currentNode.y + 1 < grid.GetHeight())
neighbourList.Add(GetNode(currentNode.x - 1, currentNode.y + 1));
}
if (currentNode.x + 1 < grid.GetWidth())
{
//right
neighbourList.Add(GetNode(currentNode.x + 1, currentNode.y));
//right down
if (currentNode.y - 1 >= 0)
neighbourList.Add(GetNode(currentNode.x + 1, currentNode.y - 1));
//right up
if (currentNode.y + 1 < grid.GetHeight())
neighbourList.Add(GetNode(currentNode.x + 1, currentNode.y + 1));
}
//down
if (currentNode.y - 1 >= 0)
neighbourList.Add(GetNode(currentNode.x, currentNode.y - 1));
//up
if (currentNode.y + 1 < grid.GetHeight())
neighbourList.Add(GetNode(currentNode.x, currentNode.y + 1));
return neighbourList;
}
public PathNode GetNode(int x, int y)
{
return grid.GetGridObject(x, y);
}
public List<Vector3> FindPathVector3(Vector3 startWorldPosition, Vector3 endWorldPosition)
{
grid.GetXY(startWorldPosition, out int startX, out int startY);
grid.GetXY(endWorldPosition, out int endX, out int endY);
List<PathNode> path = FindPath(startX, startY, endX, endY);
if (path == null)
{
return null;
}
else
{
List<Vector3> vectorPath = new List<Vector3>();
foreach(PathNode pathNode in path)
{
vectorPath.Add(new Vector3(pathNode.x, pathNode.y) * grid.GetCellSize() + Vector3.one * grid.GetCellSize() * .5f);
}
return vectorPath;
}
}
private List<PathNode> CalculatedPath(PathNode endNode)
{
List<PathNode> path = new List<PathNode>();
path.Add(endNode);
PathNode currentNode = endNode;
while (currentNode.cameFromNode != null)
{
path.Add(currentNode.cameFromNode);
currentNode = currentNode.cameFromNode;
}
path.Reverse();
return path;
}
private int CalculateDistanceCost(PathNode a,PathNode b)
{
int xDistance = Mathf.Abs(a.x - b.x);
int yDistance = Mathf.Abs(a.y - b.y);
int remaining = Mathf.Abs(xDistance - yDistance);
return MOVE_ANGLE_COST * Mathf.Min(xDistance, yDistance) + MOVE_STRAIGHT_COST * remaining;
}
private PathNode GetLowestFCost(List<PathNode> pathNodeList)
{
PathNode lowestFCostNode = pathNodeList[0];
for ( int i = 1; i < pathNodeList.Count; i++)
{
if (pathNodeList[i].fCost < lowestFCostNode.fCost)
{
lowestFCostNode = pathNodeList[i];
}
}
return lowestFCostNode;
}
}
One interesting point to note is that whenever my random point is chosen outside of the grid I have made, the error is not thrown where I would expect. Instead they claim that in my calculateDistance Cost"int xDistance = Mathf.Abs(a.x - b.x);" is not Finding an instanced Pathnode. Which makes sense because there wouldn't be one there. However, I would not expect that to be where the first error occurs with an out of bounds endpoint.

Custom A star crashes unity when enabling raycasts for walls in Unity

I decided to make my own A*. When I enable this part of the code Unity crashes.
if (Physics2D.Raycast(transform.position, a - new Vector2(current.x, current.y), 1, mask))
{
print(i);
continue;
}
There are no other objects than walls that would enable the Raycast.
The code probably enters an infinite loop, but I have no idea how because it works fine if i disable raycasts.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEditor;
using UnityEngine;
public class Star : MonoBehaviour
{
private int x, y;
private int nextX, nextY;
public Vector2 targetNode;
private Vector2 nextNode;
private List<Node> path = null;
LayerMask mask;
Bounds area;
private bool moving;
private bool check;
public float timeStart;
public Vector3 startPos;
public float speed = 1f;
float u;
Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
mask = LayerMask.GetMask("Default");
}
void FixedUpdate()
{
if (!moving)
{
Move();
}
else
MoveTo(speed);
}
private void Move()
{
area = new Bounds(transform.position, new Vector3(100, 100));
int playerX = (int)Mathf.Round(Player.x);
int playerY = (int)Mathf.Round(Player.y);
Vector2 start = new Vector2((int)transform.position.x, (int)transform.position.y);
Vector2 destination = new Vector2(playerX, playerY);
if (getDistance(start, destination) > 1f)
path = findPath(start, destination);
else
path = null;
nextX = 0;
nextY = 0;
if (path != null)
{
if (path.Count > 0)
{
nextNode = new Vector2(path[path.Count - 1].x, path[path.Count - 1].y);
if (x < nextNode.x) nextX++;
if (x > nextNode.x) nextX--;
if (y < nextNode.y) nextY++;
if (y > nextNode.y) nextY--;
}
}
if (nextX != 0 || nextY != 0)
{
Move(nextX, nextY);
}
}
public List<Node> findPath(Vector2 start, Vector2 goal)
{
x = (int)start.x;
y = (int)start.y;
List<Node> openList = new List<Node>();
List<Node> closedList = new List<Node>();
Node current = new Node(x, y, null, 0, getDistance(start, goal));
openList.Add(current);
while (openList.Count > 0)
{
openList.Sort();
current = openList[0];
if (new Vector2(current.x, current.y).Equals(goal))
{
List<Node> path = new List<Node>();
while (current.parent != null)
{
path.Add(current);
current = current.parent;
}
openList.Clear();
closedList.Clear();
return path;
}
openList.Remove(current);
closedList.Add(current);
for (int i = 0; i < 9; i++)
{
if (i == 4/* || i == 0 || i == 2 || i == 6 || i == 8*/) continue;
int x = current.x;
int y = current.y;
int xi = (i % 3) - 1; // -1, 0, 1
int yi = (i / 3) - 1;
Vector2 a = new Vector2(x + xi, y + yi);
if (Physics2D.Raycast(transform.position, a - new Vector2(current.x, current.y), 1, mask))
{
print(i);
continue;
}
double gCost = current.gCost + (getDistance(new Vector2(current.x, current.y), a));
double hCost = getDistance(a, goal);
Node node = new Node((int)a.x, (int)a.y, current, gCost, hCost); // store the node
if (!vecInList(openList, a)) openList.Add(node);
}
}
closedList.Clear();
return null;
}
private double getDistance(Vector2 tile, Vector2 goal)
{
int dx = (int)(tile.x - goal.x);
int dy = (int)(tile.y - goal.y);
return Mathf.Sqrt((dx * dx) + (dy * dy));
}
private bool vecInList(List<Node> list, Vector2 vector)
{
foreach (Node n in list)
{
Vector2 tile2 = new Vector2(n.x, n.y);
if (tile2.Equals(vector)) return true;
}
return false;
}
public void Move(int x, int y)
{
targetNode = transform.position + new Vector3(x, y);
if (area.Contains(new Vector3(Player.x, Player.y)) && (moving == false))
{
moving = true;
check = true;
}
}
public void MoveTo(float speed)
{
if (check)
{
check = false;
moving = true;
timeStart = Time.time;
startPos = transform.position;
}
if (moving)
{
u = (Time.time - timeStart) / (1 / speed);
if (u >= 1)
{
u = 1;
moving = false;
}
//transform.position = (1 - u) * (Vector2)startPos + u * targetNode;
rb.MovePosition((1 - u) * (Vector2)startPos + u * targetNode);
}
}
}
Edit: got this to work thanks to Yuri's comment. Changed to:
if (Physics2D.Raycast(new Vector2(current.x, current.y), a - new Vector2(current.x, current.y), 1, mask))
I was checking from the start position instead of the last position in the nodes.

How can I prevent from adding more and more new objects when pressing F to change formation?

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class SquadFormation : MonoBehaviour
{
enum Formation
{
Square, Circle, Triangle
}
[Header("Main Settings")]
[Space(5)]
public Transform squadMemeberPrefab;
[Range(4, 100)]
public int numberOfSquadMembers = 20;
[Range(1, 20)]
public int numberOfSquads = 1;
[Range(0, 4)]
public int columns = 4;
public int gaps = 10;
public int circleRadius = 10;
public float yOffset = 0;
[Range(3, 50)]
public float moveSpeed = 3;
[Range(3, 50)]
public float rotateSpeed = 1;
public float threshold = 0.1f;
public bool randomSpeed = false;
[Range(1, 100)]
public int randSpeedMin = 1;
[Range(1, 100)]
public int randSpeedMax = 1;
public bool startRandomFormation = false;
public string currentFormation;
private Formation formation;
private List<Quaternion> quaternions = new List<Quaternion>();
private List<Vector3> newpositions = new List<Vector3>();
private bool move = false;
private bool squareFormation = false;
private List<GameObject> squadMembers = new List<GameObject>();
private float[] step;
private int[] randomSpeeds;
private int index = 0;
private int numofobjects = 0;
// Use this for initialization
void Start()
{
numofobjects = numberOfSquadMembers;
if (startRandomFormation)
{
formation = (Formation)UnityEngine.Random.Range(0, Enum.GetNames(typeof(Formation)).Length);
}
else
{
formation = Formation.Square;
}
currentFormation = formation.ToString();
ChangeFormation();
foreach (Transform child in gameObject.transform)
{
if (child.tag == "Squad Member")
squadMembers.Add(child.gameObject);
}
randomSpeeds = RandomNumbers(randSpeedMin, randSpeedMax, squadMembers.Count);
step = new float[squadMembers.Count];
}
// Update is called once per frame
void Update()
{
if (numofobjects != numberOfSquadMembers)
{
numofobjects = 0;
numofobjects = numberOfSquadMembers;
squadMembers = new List<GameObject>();
FormationSquare();
}
if (Input.GetKeyDown(KeyCode.F))
{
randomSpeeds = RandomNumbers(randSpeedMin, randSpeedMax, squadMembers.Count);
foreach (int speedV in randomSpeeds)
{
if (index == randomSpeeds.Length)
index = 0;
step[index] = speedV * Time.deltaTime;
index++;
}
ChangeFormation();
}
if (move == true)
{
MoveToNextFormation();
}
}
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) * gaps;
float posY = (index / columns) * gaps;
return new Vector3(posX, posY);
}
private void FormationSquare()
{
newpositions = new List<Vector3>();
quaternions = new List<Quaternion>();
Transform go = squadMemeberPrefab;
for (int i = 0; i < numofobjects; i++)
{
if (squadMembers.Count == 0)
go = Instantiate(squadMemeberPrefab);
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";
go.transform.parent = gameObject.transform;
newpositions.Add(go.transform.position);
}
move = true;
squareFormation = true;
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()
{
newpositions = new List<Vector3>();
quaternions = new List<Quaternion>();
Vector3 center = transform.position;
float radius = (float)circleRadius / 2;
float angleIncrement = 360 / (float)numberOfSquadMembers;
for (int i = 0; i < numberOfSquadMembers; 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;
newpositions.Add(pos);
quaternions.Add(rot);
}
move = true;
squareFormation = false;
formation = Formation.Square;
}
private void MoveToNextFormation()
{
if (randomSpeed == false)
{
if (step.Length > 0)
step[0] = moveSpeed * Time.deltaTime;
}
for (int i = 0; i < squadMembers.Count; i++)
{
squadMembers[i].transform.LookAt(newpositions[i]);
if (randomSpeed == true)
{
squadMembers[i].transform.position =
Vector3.MoveTowards(squadMembers[i].transform.position, newpositions[i], step[i]);
}
else
{
squadMembers[i].transform.position =
Vector3.MoveTowards(squadMembers[i].transform.position, newpositions[i], step[0]);
}
if (Vector3.Distance(squadMembers[i].transform.position, newpositions[i]) < threshold)
{
if (squareFormation == true)
{
Vector3 degrees = new Vector3(0, 0, 0);
Quaternion quaternion = Quaternion.Euler(degrees);
squadMembers[i].transform.rotation = Quaternion.Slerp(squadMembers[i].transform.rotation, quaternion, rotateSpeed * Time.deltaTime);
}
else
{
squadMembers[i].transform.rotation = Quaternion.Slerp(squadMembers[i].transform.rotation, quaternions[i], rotateSpeed * Time.deltaTime);
}
}
}
}
private static int[] RandomNumbers(int min, int max, int howMany)
{
int[] myNumbers = new int[howMany];
for (int i = 0; i < howMany; i++)
{
myNumbers[i] = UnityEngine.Random.Range(min, max);
}
return myNumbers;
}
}
In the constructor I'm searching for childs with the tag Squad Member.
But the List squadMembers will be empty since the script is attached to a new empty GameObject without any childs.
Then also the variable step will be empty.
Then inside the method MoveToNextFormation I'm checking if step is empty or not:
if (step.Length > 0)
step[0] = moveSpeed * Time.deltaTime;
If not checking the it will throw exception since there is nothing at index 0 it's null. But then if step is empty there will be no speed/s at all for the objects movements.
That's one problem.
I'm not sure even why in the constructor I did the part with the children and the "Squad Member" tag. I'm not creating yet any children with this tag so I'm confused about what I tried to do in the constructor.
The second problem is in this lines in the FormationSquare method:
if (squadMembers.Count == 0)
go = Instantiate(squadMemeberPrefab);
But if squadMembers is empty then it will throw exception somewhere else in other places in the code. And I'm creating new objects inside the FormationSquare method that's since I'm starting by default with the FormationSquare but what if I want to start by default with the FormationCircle method ?
The idea is to start with minimum (1) number of squads and with minimum (4) number of members in the squad when starting the program. Or to start with any range between min and max. But it's all messed up.
In your case, I would separate the squad member prefab instantiation from the squad shape formatting, doing this will help you identify your bug.
For example add the following methods and use them during 'Start':
void AddSquadMember()
{
// Use this to instantiate/spawn a new game object prefab.
}
void AddSquadMember(GameObject object)
{
// Use this for game object already in the scene. (.eg the children with your tag)
}
Then on the formation methods remove the intantiate calls and just use whatever game object you have in the list.
Finally, I would toss the 'numofobjects' variable. Then use 'squadMembers.Count' instead of both 'numofobjects' and 'numberOfSquadMembers' assuming that during 'Start' you have taken care of instantiating all game objects in order to 'numberOfSquadMembers == squadMembers.Count'. That is because you might need to raise the squad with a few more members during gameplay.

How can i check when the object MoveTowards has reached to the new position and then rotate it?

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])
}

Categories

Resources