how to check if player has been destroyed - c#

in the game I am creating when the player dies I destroy that object and move to a different scene which simply says you died, however the camera follows the player, this creates an error when the player is destroyed as it can no longer follow the player I cannot think of how to scan to see if the player has been destroyed (from inside the cameras script)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMotor : MonoBehaviour
{
public Transform lookAt;
public float boundX = 0.001f;
public float boundY = 0.001f;
private void LateUpdate()
{
Vector3 delta = Vector3.zero;
//to check if inside the bounds on X axis
float deltaX = lookAt.position.x - transform.position.x;
if (deltaX > boundX || deltaX < -boundX)
{
if (transform.position.x < lookAt.position.x)
{
delta.x = deltaX - boundX;
}
else
{
delta.x = deltaX + boundX;
}
}
//to check if inside the bounds on Y axis
float deltaY = lookAt.position.y - transform.position.y;
if (deltaY > boundY || deltaY < -boundY)
{
if (transform.position.y < lookAt.position.y)
{
delta.y = deltaY - boundY;
}
else
{
delta.y = deltaY + boundY;
}
}
transform.position += new Vector3(delta.x, delta.y, 0);
}
}

Check if lookAt is not null before looking at the player...
private void LateUpdate()
{
if(lookAt != null){
Vector3 delta = Vector3.zero;
//to check if inside the bounds on X axis
float deltaX = lookAt.position.x - transform.position.x;
if (deltaX > boundX || deltaX < -boundX)
{
if (transform.position.x < lookAt.position.x)
{
delta.x = deltaX - boundX;
}
else
{
delta.x = deltaX + boundX;
}
}
//to check if inside the bounds on Y axis
float deltaY = lookAt.position.y - transform.position.y;
if (deltaY > boundY || deltaY < -boundY)
{
if (transform.position.y < lookAt.position.y)
{
delta.y = deltaY - boundY;
}
else
{
delta.y = deltaY + boundY;
}
}
transform.position += new Vector3(delta.x, delta.y, 0);
}
}

When the object is destroyed, it's components are destroyed too. So You can simply check if Transform object is null.
if (lookAt == null)
{
Debug.Log("Object has destroyed");
}

Related

UNITY C#..my enemys are piling up with vector2.move towards

hi there thanks for taking the time to look at my question
im currenty making a 2D side scroller/platformer and im currently facing a issue where my enemies are piling up on top of each other. through googling i see alot of Astar pathfinding solving this however i hesitant to jump into ai right now as i glanced over its internal scripts and they are outside my current knowledge and im still attempting to get a understanding of just using scripting to achieve what i want.
i currently have my enemies correctly chasing my player with a vector2.movetowards however eventually they all pile on each other.
through google i have found this is a typical outcome of movetowards and i found this solution
https://answers.unity.com/questions/1608266/stop-enemies-from-grouping-up.html
and i implemented its code
void avoidOthers()
{
var hits = Physics2D.OverlapCircleAll(enemy.transform.position, avoidenceRadius);//create a circle around each enemy and check to see if they are not colliding
foreach (var hit in hits)
{
if(hit.GetComponent<DartFish>() != null && hit.transform != transform)//check to see if it is a enemy
{
Debug.Log("enemy transform" + enemy.transform.position);
Debug.Log("hit transform" + hit.transform.position);
Vector2 difference = enemy.transform.position - hit.transform.position;//check how close we are to another enemy
difference = difference.normalized / Mathf.Abs(difference.magnitude);//calculate how long the vector is
sum += difference;//add together differences so we can calculate a average of the group
count++;
}
}
if(count > 0)// if we found enemys interfearing with each other
{
sum /= count;//average of the movement
sum = sum.normalized * avoidenceSpeed;//calculate movement speed
Debug.Log("sum = " + sum);
enemy.transform.position = Vector2.MoveTowards(enemy.transform.position, enemy.transform.position + (Vector3)sum, avoidenceSpeed * Time.deltaTime);
}
}
however i needed to add "enemy" to each transform.position or they would instantly snap from my spawn location to the player.
after adding enemy they stopped snapping over a large distance except now they started piling again
all of my debug logs look like they are printing out the correct values
i was also reading through transform.translate as looking at my "sum" values this should be how much they are moving away from each other
so i changed the line
enemy.transform.position = Vector2.MoveTowards(enemy.transform.position, enemy.transform.position + (Vector3)sum, avoidenceSpeed * Time.deltaTime);
to
transform.Translate((Vector3)sum * avoidenceSpeed * Time.deltaTime, Space.World);
now it seems to only effect one fish and the others clump together still
from my understanding physics.overlapcircle all should be functioning as a list?
heres my entire code albeit long(still relatively new to coding)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DartFish : MonoBehaviour
{
public Transform target;
public float movementSpeed;
private float initialMovementSpeed;
public float dashSpeed;
private float spawnSpeed = 1.5f;
public float chaseRadius;
private float initialChaseRadius;
public float dashRadius;
private Vector2 targetDirection;
private float directionX;
private float previousDirectionX;
private float directionY;
private float spriteAngle;
private float previousAngle;
private float currentSpriteAngle;
private float difference;
private SpriteRenderer mySpriteRenderer;
private Rigidbody2D myRigidbody;
private bool directionIsAboutToChange;
private bool directionHasChanged;
private Vector3 angleCompensation;
// avoid others variables
public float avoidenceSpeed;
public float avoidenceRadius;
public Transform enemy;
private Vector2 sum = Vector2.zero;
private float count;
// Start is called before the first frame update
void Start()
{
enemy = GameObject.FindWithTag("dartfish").transform;
target = GameObject.FindWithTag("Player").transform;
mySpriteRenderer = GetComponent<SpriteRenderer>();
myRigidbody = GetComponent<Rigidbody2D>();
initialMovementSpeed = movementSpeed;
initialChaseRadius = chaseRadius;
}
// Update is called once per frame
void Update()
{
targetDirection = target.position - transform.position;// where is the player?
directionX = targetDirection.x;//extract only x for "check direction"
directionY = targetDirection.y;
if(directionX < -initialChaseRadius + .5f)// is the player further then the chase radius?
{
myRigidbody.velocity = new Vector2(-1.5f, 0);
}
else
{
myRigidbody.velocity = Vector2.zero;
}
if(directionX > 0)//calculate tangent angle to the player in radians and then convert it to degrees
{
spriteAngle = Mathf.Atan2(targetDirection.y, targetDirection.x) * Mathf.Rad2Deg;
}
else if(directionX < 0)//if player is to the left flip opp/adj and add 100° to zero angle
{
spriteAngle = Mathf.Atan2(targetDirection.x, targetDirection.y) * Mathf.Rad2Deg +100f;
}
currentSpriteAngle = spriteAngle;
difference = spriteAngle - previousAngle;
difference = Mathf.Abs(difference);
if(directionX < 1 && directionX > -1)//are we about to change directions?
{
//Debug.Log("direction is about to change");
directionIsAboutToChange = true;
}
if(directionIsAboutToChange == true)//did we pass through trigger zone?
{
if(directionX > 1 || directionX < -1)
//Debug.Log("direction has changed");
directionHasChanged = true;
}
lookAtMe();
chaseMe();
avoidOthers();
/*
//debug logs with spam control
if(previousAngle != spriteAngle)
{
Debug.Log("angle = " + spriteAngle);
}
if(difference != 0)
{
Debug.Log("difference = " + difference);
}
if(previousDirectionX != directionX)
{
Debug.Log("directionX = " + directionX);
}
if(previousAngle != currentSpriteAngle)
{
Debug.Log("previous angle = " + previousAngle);
}
*/
previousAngle = currentSpriteAngle;
previousDirectionX = directionX;
}
void lookAtMe()
{
if(directionHasChanged == true)//angle compensation for sprite flip
{
if(directionY > 0)//is the player above or below us
{
angleCompensation = transform.localEulerAngles;//get current rotation
//flip it
if(directionX > 0)
{
transform.localEulerAngles = -angleCompensation;
}
if(directionX < 0)
{
transform.localEulerAngles = angleCompensation;
}
}
if(directionY < 0)
{
if(directionX > 0)
{
transform.localEulerAngles = angleCompensation;
}
if(directionX < 0)
{
transform.localEulerAngles = -angleCompensation;
}
}
directionHasChanged = false;
directionIsAboutToChange = false;
}
if(directionX < -1)
{
mySpriteRenderer.flipX = true;
//Debug.Log("entered void lookAtMe.directionX <");
if(spriteAngle > previousAngle && spriteAngle < 50f )
{
transform.Rotate(0f, 0f, -difference);
}
else if(spriteAngle < previousAngle && spriteAngle > -50f)
{
transform.Rotate(0f, 0f, difference);
}
}
else if(directionX > 1)
{
mySpriteRenderer.flipX = false;
//Debug.Log("entered void lookAtMe.directionX >");
if(spriteAngle > previousAngle && spriteAngle < 50f)
{
transform.Rotate(0f, 0f, difference);
}
else if(spriteAngle < previousAngle && spriteAngle > -50f)
{
transform.Rotate(0f, 0f, -difference);
}
}
}
void avoidOthers()
{
var hits = Physics2D.OverlapCircleAll(enemy.transform.position, avoidenceRadius);//create a circle around each enemy and check to see if they are not colliding
foreach (var hit in hits)
{
if(hit.GetComponent<DartFish>() != null && hit.transform != transform)//check to see if it is a enemy
{
Debug.Log("enemy transform" + enemy.transform.position);
Debug.Log("hit transform" + hit.transform.position);
Vector2 difference = enemy.transform.position - hit.transform.position;//check how close we are to another enemy
difference = difference.normalized / Mathf.Abs(difference.magnitude);//calculate how long the vector is
sum += difference;//add together differences so we can calculate a average of the group
count++;
}
}
if(count > 0)// if we found enemys interfearing with each other
{
sum /= count;//average of the movement
sum = sum.normalized * avoidenceSpeed;//calculate movement speed
Debug.Log("sum = " + sum);
transform.Translate((Vector3)sum * avoidenceSpeed * Time.deltaTime, Space.World);
}
}
void chaseMe()
{
if(Vector3.Distance(target.position, transform.position) <= chaseRadius && Vector3.Distance(target.position, transform.position) > dashRadius)
{
transform.position = Vector3.MoveTowards(transform.position, target.position, movementSpeed * Time.deltaTime);
}
else if(Vector3.Distance(target.position, transform.position) <= dashRadius)
{
transform.position = Vector3.MoveTowards(transform.position, target.position, dashSpeed * Time.deltaTime);
}
}
}
please help me stop my enemys from clumping up without the use of AI
thanks again for any assistance and your time its much appreciated

How to make the turret that shoot laser to targets to choose the closet target each time and shoot the laser towards the closet target?

For example there are 5 target and they are moving randomly around the turret.
Now i'm using only one target targets[0] and the turret is rotating facing the target and shoot laser to it.
Now i want to make it with multiple targets and that the turret will choose each time the closet target and will shoot to it the laser.
I changed this part added a for loop over the targets :
for (int i = 0; i < targets.Count; i++)
but i'm still using only one target, targets[0] i'm not sure how to add the distance part and the closet target choosing.
I tried this solution but now the turret(transform) is not rotating at all towards the selected target. for some reason this two lines return null on the closestTarget :
RotateToMouseDirection(gameObject, closestTarget.position);
The script with the changes :
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System;
using UnityEngine;
public class Hovl_DemoLasers : MonoBehaviour
{
public List<Transform> targets;
public GameObject FirePoint;
public Camera Cam;
public float MaxLength;
public GameObject[] Prefabs;
private Ray RayMouse;
private Vector3 direction;
private Quaternion rotation;
[Header("GUI")]
private float windowDpi;
private int Prefab;
private GameObject Instance;
private Hovl_Laser LaserScript;
private Hovl_Laser2 LaserScript2;
private bool rotateMouse = true;
private bool startLaser = true;
private float buttonSaver = 0f;
private Hovl_LaserDemo hovl_laserDemo;
private float maxDistance = 0;
private float distance;
private Transform closestTarget;
void Start ()
{
if (Screen.dpi < 1) windowDpi = 1;
if (Screen.dpi < 200) windowDpi = 1;
else windowDpi = Screen.dpi / 200f;
Counter(0);
}
void Update()
{
//Enable lazer
if (Input.GetMouseButtonDown(0))
{
Destroy(Instance);
Instance = Instantiate(Prefabs[Prefab], FirePoint.transform.position, FirePoint.transform.rotation);
Instance.transform.parent = transform;
LaserScript = Instance.GetComponent<Hovl_Laser>();
LaserScript2 = Instance.GetComponent<Hovl_Laser2>();
rotateMouse = true;
}
if (Input.GetMouseButtonDown(1))
{
rotateMouse = false;
}
//Disable lazer prefab
if (Input.GetMouseButtonUp(0))
{
/*if (LaserScript) LaserScript.DisablePrepare();
if (LaserScript2) LaserScript2.DisablePrepare();
Destroy(Instance,1);*/
}
if ((Input.GetKey(KeyCode.A) || Input.GetAxis("Horizontal") < 0) && buttonSaver >= 0.4f)// left button
{
buttonSaver = 0f;
Counter(-1);
}
if ((Input.GetKey(KeyCode.D) || Input.GetAxis("Horizontal") > 0) && buttonSaver >= 0.4f)// right button
{
buttonSaver = 0f;
Counter(+1);
}
buttonSaver += Time.deltaTime;
if (startLaser)
{
rotateMouse = false;
Destroy(Instance);
Instance = Instantiate(Prefabs[Prefab], FirePoint.transform.position, FirePoint.transform.rotation);
Instance.transform.parent = transform;
LaserScript = Instance.GetComponent<Hovl_Laser>();
LaserScript2 = Instance.GetComponent<Hovl_Laser2>();
hovl_laserDemo = Instance.GetComponent<Hovl_LaserDemo>();
startLaser = false;
}
if (targets != null)
{
for (int i = 0; i < targets.Count; i++)
{
distance = Vector3.Distance(transform.position, targets[i].position);
if (distance < maxDistance)
{
maxDistance = distance;
closestTarget = targets[i];
}
}
if (hovl_laserDemo != null)
{
MaxLength = distance;
hovl_laserDemo.MaxLength = distance;
}
if (Cam != null)
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, MaxLength))
{
RotateToMouseDirection(gameObject, closestTarget.position);
}
else
{
RotateToMouseDirection(gameObject, closestTarget.position);
}
}
}
if (Cam != null && rotateMouse)
{
RaycastHit hit;
var mousePos = Input.mousePosition;
RayMouse = Cam.ScreenPointToRay(mousePos);
if (Physics.Raycast(RayMouse.origin, RayMouse.direction, out hit, MaxLength))
{
RotateToMouseDirection(gameObject, hit.point);
}
else
{
var pos = RayMouse.GetPoint(MaxLength);
RotateToMouseDirection(gameObject, pos);
}
}
else
{
Debug.Log("No camera");
}
}
void OnGUI()
{
GUI.Label(new Rect(10 * windowDpi, 5 * windowDpi, 400 * windowDpi, 20 * windowDpi), "Use the keyboard buttons A/<- and D/-> to change lazers!");
GUI.Label(new Rect(10 * windowDpi, 20 * windowDpi, 400 * windowDpi, 20 * windowDpi), "Use left mouse button for shooting!");
}
void Counter(int count)
{
Prefab += count;
if (Prefab > Prefabs.Length - 1)
{
Prefab = 0;
}
else if (Prefab < 0)
{
Prefab = Prefabs.Length - 1;
}
}
void RotateToMouseDirection (GameObject obj, Vector3 destination)
{
direction = destination - obj.transform.position;
rotation = Quaternion.LookRotation(direction);
obj.transform.localRotation = Quaternion.Lerp(obj.transform.rotation, rotation, 1);
}
}
The old original script before the changes :
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization.Formatters;
using System;
using UnityEngine;
public class DemoLasers : MonoBehaviour
{
public List<Transform> targets;
public GameObject FirePoint;
public Camera Cam;
public float MaxLength;
public GameObject[] Prefabs;
private Ray RayMouse;
private Vector3 direction;
private Quaternion rotation;
[Header("GUI")]
private float windowDpi;
private int Prefab;
private GameObject Instance;
private Hovl_Laser LaserScript;
private Hovl_Laser2 LaserScript2;
private bool rotateMouse = true;
private bool startLaser = true;
private float buttonSaver = 0f;
private Hovl_LaserDemo hovl_laserDemo;
void Start ()
{
if (Screen.dpi < 1) windowDpi = 1;
if (Screen.dpi < 200) windowDpi = 1;
else windowDpi = Screen.dpi / 200f;
Counter(0);
}
void Update()
{
//Enable lazer
if (Input.GetMouseButtonDown(0))
{
Destroy(Instance);
Instance = Instantiate(Prefabs[Prefab], FirePoint.transform.position, FirePoint.transform.rotation);
Instance.transform.parent = transform;
LaserScript = Instance.GetComponent<Hovl_Laser>();
LaserScript2 = Instance.GetComponent<Hovl_Laser2>();
rotateMouse = true;
}
if (Input.GetMouseButtonDown(1))
{
rotateMouse = false;
}
if ((Input.GetKey(KeyCode.A) || Input.GetAxis("Horizontal") < 0) && buttonSaver >= 0.4f)// left button
{
buttonSaver = 0f;
Counter(-1);
}
if ((Input.GetKey(KeyCode.D) || Input.GetAxis("Horizontal") > 0) && buttonSaver >= 0.4f)// right button
{
buttonSaver = 0f;
Counter(+1);
}
buttonSaver += Time.deltaTime;
if (startLaser)
{
rotateMouse = false;
Destroy(Instance);
Instance = Instantiate(Prefabs[Prefab], FirePoint.transform.position, FirePoint.transform.rotation);
Instance.transform.parent = transform;
LaserScript = Instance.GetComponent<Hovl_Laser>();
LaserScript2 = Instance.GetComponent<Hovl_Laser2>();
hovl_laserDemo = Instance.GetComponent<Hovl_LaserDemo>();
startLaser = false;
}
if (targets != null)
{
for (int i = 0; i < targets.Count; i++)
{
if (hovl_laserDemo != null)
{
float distance = Vector3.Distance(gameObject.transform.position, targets[0].position);
MaxLength = distance;
hovl_laserDemo.MaxLength = distance;
}
if (Cam != null)
{
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, MaxLength))
{
RotateToMouseDirection(gameObject, targets[0].position);
}
else
{
RotateToMouseDirection(gameObject, targets[0].position);
}
}
}
}
if (Cam != null && rotateMouse)
{
RaycastHit hit;
var mousePos = Input.mousePosition;
RayMouse = Cam.ScreenPointToRay(mousePos);
if (Physics.Raycast(RayMouse.origin, RayMouse.direction, out hit, MaxLength))
{
RotateToMouseDirection(gameObject, hit.point);
}
else
{
var pos = RayMouse.GetPoint(MaxLength);
RotateToMouseDirection(gameObject, pos);
}
}
else
{
Debug.Log("No camera");
}
}
void OnGUI()
{
GUI.Label(new Rect(10 * windowDpi, 5 * windowDpi, 400 * windowDpi, 20 * windowDpi), "Use the keyboard buttons A/<- and D/-> to change lazers!");
GUI.Label(new Rect(10 * windowDpi, 20 * windowDpi, 400 * windowDpi, 20 * windowDpi), "Use left mouse button for shooting!");
}
void Counter(int count)
{
Prefab += count;
if (Prefab > Prefabs.Length - 1)
{
Prefab = 0;
}
else if (Prefab < 0)
{
Prefab = Prefabs.Length - 1;
}
}
void RotateToMouseDirection (GameObject obj, Vector3 destination)
{
direction = destination - obj.transform.position;
rotation = Quaternion.LookRotation(direction);
obj.transform.localRotation = Quaternion.Lerp(obj.transform.rotation, rotation, 1);
}
}
Have 2 Variables in a Loop.
one is the index of the current closest target in you List,
and the other one the distance
int closestIndex = 0;
float maxDistance = 0;
for (int i = 0; i < targets.Count; i++)
{
//Here we calculate the distance of the current pos
//You can take any Formula e.g. the Manhattan Formula
float distance = Vector3.Distance(turretPositionOrSth, targets[i].position);
//if the distance is shorter than the current max Distance
if (distance < maxDistance)
{
maxDistance = distance;
closestIndex = i;
}
}
//Now you have your Index in the list to the closest Target,which you can use
//you can use now for example targets[closestIndex] for aiming or so
Also you don't need your already written loop anymore
Here's essentially the same answer as tthe one #cpaech gave, but there was a couple issues.
int closestIndex = 0;
float minDistance = float.MaxValue;
for (int i = 0; i < targets.Count; i++)
{
//Here we calculate the distance of the current pos
//You can take any Formula e.g. the Manhattan Formula
float distance = Vector3.Distance(turretPositionOrSth, targets[i].position);
//if the distance is shorter than the current max Distance
if (distance < maxDistance)
{
maxDistance = distance;
closestIndex = i;
}
}
It could also be helpful to have an attribute for the closest target and have
if (distance < maxDistance)
{
maxDistance = distance;
closestTarget = targets[i];
}
It looks like you have two requirements -- to find not just the closest enemy, but the closest enemy with direct line of sight to the turret?
You could sort the list of enemies by distance to the turret and iterate over it from closest to furthest until a valid target is found (requiring fewer raycasts might provide a small performance advantage if there were a massive number of enemies), or you could just try the raycast on every enemy, but here's a compromise that only tries the raycast if the enemy is closer than any previous enemy tested.
Transform target = null;
float lowestDistance = float.MaxValue;
if( cam != null && hovl_laserDemo != null && targets != null )
{
for( int i = 0; i < targets.Count; i++ )
{
float distance = Vector3.Distance(gameObject.transform.position, targets[i].position);
if( distance < lowestDistance )
{
RaycastHit hit;
if( Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, distance)
&& hit.transform == targets[i] )
{
// If our raycast successfully reached the intended target without being blocked by anything else
lowestDistance = distance;
target = targets[i];
}
}
}
}
if( target != null )
{
MaxLength = lowestDistance;
hovl_laserDemo.MaxLength = lowestDistance;
RotateToMouseDirection(gameObject, target.position);
}
else
{
// Do whatever you want to do when there is no valid target
}
Edit: Actually it looks like your raycast was succeeding if it hit anything, not just the intended target. I've tried to correct that above.

Line of Sight with Ray in XNA/Monogame

I'm trying to create a Line of Sight method for an enemy class. However, it always returns false, no matter how close the player is to the enemy or whether the ray passes through any blocks to get to the player.
public virtual bool PlayerInLOS()
{
Vector3 middleOfPlayer = new Vector3(Level.Player.Position.X, Level.Player.Position.Y - Level.Player.BoundingRectangle.Height / 2, 0);
Vector3 middleOfEnemy = new Vector3(Position.X, Position.Y - localBounds.Height / 2, 0);
Vector3 direction = middleOfPlayer - middleOfEnemy;
float distanceToPlayer = Vector3.Distance(middleOfEnemy, middleOfPlayer);
if (direction != Vector3.Zero)
direction.Normalize();
Ray lineOfSight = new Ray(middleOfEnemy, direction);
float? lineToPlayer = lineOfSight.Intersects(Level.Player.BoundingBox);
foreach (BoundingBox box in Level.boundingBoxes)
{
float? distanceToIntersect = lineOfSight.Intersects(box);
if (distanceToIntersect == null)
continue;
else if (distanceToIntersect < visionLength && distanceToIntersect < distanceToPlayer && distanceToIntersect != null)
return false;
}
// Never gets to this part because it always returns before it exits the for loop
if (lineToPlayer < visionLength)
return true;
else return false;
}
Any ideas? Thanks.
I ended up fixing the problem by implementing an entirely different solution: checking every Vector2 along the distance between the enemy and the player. Works perfectly.
public bool CanSeePlayer()
{
Vector2 middleOfPlayer = new Vector2(Level.Player.Position.X, Level.Player.Position.Y - Level.Player.BoundingRectangle.Height / 2);
Vector2 middleOfEnemy = new Vector2(Position.X, Position.Y - localBounds.Height / 2);
Vector2 direction = middleOfPlayer - middleOfEnemy;
float distanceToPlayer = Vector2.Distance(middleOfEnemy, middleOfPlayer);
if (visionLength > distanceToPlayer) // If the enemy can see farther than the player's distance,
{
if (direction != Vector2.Zero)
direction.Normalize();
for (int y = 0; y < Level.tiles.GetLength(1); ++y) // loop through every tile,
{
for (int x = 0; x < Level.tiles.GetLength(0); ++x)
{
if (Level.GetCollision(x, y) != TileCollision.Passable) // and if the block is solid,
{
Vector2 currentPos = middleOfEnemy;
float lengthOfLine = 0.0f;
Rectangle tileRect = new Rectangle(x * Tile.Width, y * Tile.Height, Tile.Width, Tile.Height);
while (lengthOfLine < distanceToPlayer + 1.0f) // check every point along the line
{
currentPos += direction;
if (tileRect.Contains(currentPos)) // to see if the tile contains it.
{
return false;
}
lengthOfLine = Vector2.Distance(middleOfEnemy, currentPos);
}
}
}
}
// If every tile does not contain a single point along the line from the enemy to the player,
return true;
}
return false;
}
If you need to check if enemy is within angle of sight, and in some distance you could try this code.
public static bool InLOS(float AngleDistance, float PositionDistance, Vector2 PositionA, Vector2 PositionB, float AngleB)
{
float AngleBetween = (float)Math.Atan2((PositionA.Y - PositionB.Y), (PositionA.X - PositionB.X));
if ((AngleBetween <= (AngleB + (AngleDistance / 2f / 100f))) && (AngleBetween >= (AngleB - (AngleDistance / 2f / 100f))) && (Vector2.Distance(PositionA, PositionB) <= PositionDistance)) return true;
else return false;
}
credits: https://gamedev.stackexchange.com/questions/26813/xna-2d-line-of-sight-check

Pinch-To-Zoom with Unity 5 UI

I'm trying to re-implement a pinch-to-zoom system in a Unity UI-based app. About six months ago I was able to hack one together by making the UI canvas a child of a regular GameObject, and manipulating that object's transform, but since updating to Unity 5.5+ I find this doesn't work. The closest I can get allows the pinch gesture to change the canvas' scaleFactor, which a) can make images, panels, etc resize improperly depending on their alignments, and b) won't allow me to pan once zoomed.
What I have so far is this:
public class PinchToZoomScaler : MonoBehaviour {
public Canvas canvas; // The canvas
public float zoomSpeed = 0.5f; // The rate of change of the canvas scale factor
public float _resetDuration = 3.0f;
float _durationTimer = 0.0f;
float _startScale = 0.0f;
void Start() {
_startScale = canvas.scaleFactor;
}
void Update()
{
// If there are two touches on the device...
if (Input.touchCount == 2) {
// Store both touches.
Touch touchZero = Input.GetTouch (0);
Touch touchOne = Input.GetTouch (1);
// Find the position in the previous frame of each touch.
Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
// Find the magnitude of the vector (the distance) between the touches in each frame.
float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;
// Find the difference in the distances between each frame.
float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;
// ... change the canvas size based on the change in distance between the touches.
canvas.scaleFactor -= deltaMagnitudeDiff * zoomSpeed;
// Make sure the canvas size never drops below 0.1
canvas.scaleFactor = Mathf.Max (canvas.scaleFactor, _startScale);
canvas.scaleFactor = Mathf.Min (canvas.scaleFactor, _startScale * 3.0f);
_durationTimer = 0.0f;
} else {
_durationTimer += Time.deltaTime;
if (_durationTimer >= _resetDuration) {
canvas.scaleFactor = _startScale;
}
}
}
}
As I said, this works to a degree, but doesn't give me a nice uniform zooming, not does it allow me to pan the canvas. Thanks in advance for any help.
Attach this script in canvas object which you want to zoom in and zoom out by pinch
using UnityEngine;
using UnityEngine.EventSystems;
public class ObjectScalling : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
private bool _isDragging;
private float _currentScale;
public float minScale, maxScale;
private float _temp = 0;
private float _scalingRate = 2;
private void Start()
{
_currentScale = transform.localScale.x;
}
public void OnPointerDown(PointerEventData eventData)
{
if (Input.touchCount == 1)
{
_isDragging = true;
}
}
public void OnPointerUp(PointerEventData eventData)
{
_isDragging = false;
}
private void Update()
{
if (_isDragging)
if (Input.touchCount == 2)
{
transform.localScale = new Vector2(_currentScale, _currentScale);
float distance = Vector3.Distance(Input.GetTouch(0).position, Input.GetTouch(1).position);
if (_temp > distance)
{
if (_currentScale < minScale)
return;
_currentScale -= (Time.deltaTime) * _scalingRate;
}
else if (_temp < distance)
{
if (_currentScale > maxScale)
return;
_currentScale += (Time.deltaTime) * _scalingRate;
}
_temp = distance;
}
}
}
Reminder: This script only works in canvas objects
You can use this function ( just pass to it negative deltaMagnitudeDiff )
Also it is good to multiplay deltaMagnitudeDiff with a ratio like ( 0.05 )
float currentScale = 1f;
void Zoom (float increment)
{
currentScale += increment;
if (currentScale >= maxScale)
{
currentScale = maxScale;
}
else if (currentScale <= minScale)
{
currentScale = minScale;
}
rectTransform.localScale = new Vector3 (currentScale, currentScale, 1);
pan.ValidatePosition ();
}
For Panning,
you can use something like this :
public class Pan : MonoBehaviour
{
public float Speed;
Vector3 startDragPosition;
public void BeginDrag ()
{
startDragPosition = Input.mousePosition;
}
public void Drag ()
{
transform.localPosition += (Input.mousePosition - startDragPosition) * Speed;
startDragPosition = Input.mousePosition;
ValidatePosition ();
}
public void ValidatePosition ()
{
var temp = transform.localPosition;
var width = ((RectTransform)transform).sizeDelta.x;
var height = ((RectTransform)transform).sizeDelta.y;
var MaxX = 0.5f * width * Mathf.Max (0, transform.localScale.x - 1);
var MaxY = 0.5f * height * Mathf.Max (0, transform.localScale.y - 1);
var offsetX = transform.localScale.x * width * (((RectTransform)transform).pivot.x - 0.5f);
var offsetY = transform.localScale.y * width * (((RectTransform)transform).pivot.y - 0.5f);
if (temp.x < -MaxX + offsetX)
temp.x = -MaxX + offsetX;
else if (temp.x > MaxX + offsetX)
temp.x = MaxX + offsetX;
if (temp.y < -MaxY + offsetY)
temp.y = -MaxY + offsetY;
else if (temp.y > MaxY + offsetY)
temp.y = MaxY + offsetY;
transform.localPosition = temp;
}
Just call the functions ( BeginDrag & Drag ) from the Events Trigger component.
what i did to scale an object using pinch was this, it works on any touch screen when the object is in the middle of the screen:
if (Input.touchCount == 2)
{
//The distance between the 2 touches is checked and subsequently used to scale the
//object by moving the 2 fingers further, or closer form eachother.
Touch touch0 = Input.GetTouch(0);
Touch touch1 = Input.GetTouch(1);
if (isScaling)//this will only be done if scaling is true
{
float currentTouchDistance = getTouchDistance();
float deltaTouchDistance = currentTouchDistance - touchDistanceOrigin;
float scalePercentage = (deltaTouchDistance / 1200f) + 1f;
Vector3 scaleTemp = transform.localScale;
scaleTemp.x = scalePercentage * originalScale.x;
scaleTemp.y = scalePercentage * originalScale.y;
scaleTemp.z = scalePercentage * originalScale.z;
//to make the object snap to 100% a check is being done to see if the object scale is close to 100%,
//if it is the scale will be put back to 100% so it snaps to the normal scale.
//this is a quality of life feature, so its easy to get the original size of the object.
if (scaleTemp.x * 100 < 102 && scaleTemp.x * 100 > 98)
{
scaleTemp.x = 1;
scaleTemp.y = 1;
scaleTemp.z = 1;
}
//here we apply the calculation done above to actually make the object bigger/smaller.
transform.localScale = scaleTemp;
}
else
{
//if 2 fingers are touching the screen but isScaling is not true we are going to see if
//the middle of the screen is looking at the object and if it is set isScalinf to true;
Ray ray;
RaycastHit hitTouch;
ray = cam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
if (Physics.Raycast(ray, out hitTouch, 100f))
{
if (hitTouch.transform == transform)
{
isScaling = true;
//make sure that the distance between the fingers on initial contact is used as the original distance
touchDistanceOrigin = getTouchDistance();
originalScale = transform.localScale;
}
}
}
}

Unity - OnTriggerEnter bullet ricochet

i have some problems with simple ballistics.As i am new to coding and i wasted 2 days with searching, i decided to ask a question. I have a problem with my bullet.cs script, code works fine, except ricochet part. I used OnTriggerEnter beacuse bullets will penetrate different materials, but will bounce under specific angles, so i used collider as a trigger only. I know it can be dobe using OnCollisionEnter to determine normal and use Vector3.Reflect. But if collider is not set as a trigger only, bullets will be bouncing off from everithing a will never penetrate a wall. Just need a help with ricochet part on the bottom.
public Rigidbody rb;
private float vel;
private float kEnergy;
private bool AP = false;
private bool HP = false;
private bool ricochet = false;
// Use this for initialization
void Start () {
vel = 738f;
kEnergy = 2108f;
//HP == false;
Destroy (gameObject, 10);
rb = GetComponent<Rigidbody> ();
rb.velocity = transform.forward * vel;
Quaternion bulletRotaion = transform.rotation;
Debug.Log (bulletRotaion.eulerAngles);
}
// Update is called once per frame
void Update () {
float curVelocity = rb.velocity.magnitude;
if (curVelocity <= 0)
{
curVelocity = 0f;
}
}
void OnTriggerEnter (Collider c)
{
if (c.tag == "Wall") {
Quaternion localOffset = transform.rotation;
float impactAngleX = c.gameObject.GetComponent <MaterialDensity> ().angleX;
float impactAngleY = c.gameObject.GetComponent <MaterialDensity> ().angleY;
float impactAngleZ = c.gameObject.GetComponent <MaterialDensity> ().angleZ;
float angleX = localOffset.eulerAngles.x;
float angleY = localOffset.eulerAngles.y;
float angleZ = localOffset.eulerAngles.z;
float density = c.gameObject.GetComponent <MaterialDensity> ().materialDensity;
float ricochetX = (angleX + impactAngleX);
if (ricochetX > 360)
{
ricochetX = (ricochetX - 360);
}
if (ricochetX < 0)
{
ricochetX = (ricochetX + 360);
}
float ricochetY = (angleY + impactAngleY);
if (ricochetY > 360)
{
ricochetY = (ricochetY - 360);
}
if (ricochetY < 0)
{
ricochetY = (ricochetY + 360);
}
float ricochetZ = (angleZ + impactAngleZ);
if (ricochetZ > 360)
{
ricochetZ = (ricochetZ - 360);
}
if (ricochetZ < 0)
{
ricochetZ = (ricochetZ + 360);
}
if ((ricochetX > 60 && ricochetX < 300) || (ricochetY > 60 && ricochetY < 300) || (ricochetZ > 60 && ricochetZ < 300)) {
ricochet = true;
//Debug.Log (ricochet);
}
if ((ricochetX < 60 && ricochetX > 300) || (ricochetY < 60 && ricochetY > 300) || (ricochetZ < 60 && ricochetZ > 300)) {
ricochet = false;
//Debug.Log (ricochet);
}
Debug.Log (ricochet);
Debug.Log (ricochetX);
Debug.Log (ricochetY);
Debug.Log (ricochetZ);
if (AP)
{
density *= 0.9f;
}
if (HP)
{
density *= 3f;
}
//float vel = gameObject.GetComponent<GunNew>().velocity;
float curVelocity = rb.velocity.magnitude;
float velocityMod = curVelocity / vel;
float densityMod = density / velocityMod;
float curEnergy = (kEnergy * velocityMod);
float energyMod = (curEnergy * velocityMod);
rb = GetComponent<Rigidbody> ();
//Quaternion localOffset = transform.rotation;
float randomX = Random.Range (0.03f, 0f);
float randomY = Random.Range (0.03f, -0.03f);
if (randomX == 0)
{
randomX = 0.01f;
}
if (randomY == 0)
{
randomY = 0.01f;
}
localOffset.x += randomX;
localOffset.y += randomY;
if (curVelocity > densityMod && !ricochet) {
rb.rotation = localOffset;
rb.velocity = transform.forward * ((curVelocity - (curVelocity * (randomX + randomY))) - densityMod);
//Debug.Log (curVelocity);
//Debug.Log (energyMod);
}
if (curVelocity > densityMod && ricochet)
{
Vector3 objAngle = new Vector3 (impactAngleX, impactAngleY, impactAngleZ);
Vector3 bulletAngle = rb.rotation.eulerAngles;
Debug.Log (objAngle);
}
if (curVelocity <= densityMod)
{
//Debug.Log (curVelocity);
//Debug.Log (energyMod);
Destroy (gameObject);
}
}
}
second code is a code from wall.
public float materialDensity = 100f;
public float angleX;
public float angleY;
public float angleZ;
//Quaternion localOffset = transform.rotation;
// Use this for initialization
public void Start ()
{
GetComponent<Rigidbody> ();
Quaternion localOffset = transform.rotation;
float angleX = localOffset.eulerAngles.x;
float angleY = localOffset.eulerAngles.y;
float angleZ = localOffset.eulerAngles.z;
//Debug.Log (localOffset.eulerAngles.x);
}
// Update is called once per frame
void Update () {
}
Firstly, I would make a layers in your game for things that will ricochet, and things that don't.
Then when you test for collisions with your bullet you can only check for collisions with the ricochet layer. This will increase performance and also make coding much simpler.
From there you could rely on unity's physics to do it's own ricochet, or if you wanted to calculate it yourself you could do a raycast and use the raycast's normal as described above.
if(Physics.Raycast (shootRay, out shootHit, range, ricochetMask)) {
...

Categories