RayCast2D ignor hitting own Collider - unity3d

Board.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Board : MonoBehaviour
{
public Transform m_emptySprite;
private int m_height = 14;
private int m_width = 6;
// number of rows where we won't have grid lines at the top
public int m_header = 8;
// Start is called before the first frame update
void Start()
{
DrawEmptyCells();
}
void DrawEmptyCells()
{
for (int y = 0; y < m_height - m_header; y++)
{
for (int x = 0; x < m_width; x++)
{
Transform tile;
tile = Instantiate(m_emptySprite, new Vector3(x, y, 0), Quaternion.identity) as Transform;
tile.name = "Tile ( x = " + x.ToString() + " ,y = " + y.ToString() + ")";
tile.transform.parent = transform;
}
}
}
}
Tile.cs
public class Tile : MonoBehaviour
{
private Vector2[] adjacentDirections = new Vector2[] { Vector2.up, Vector2.down, Vector2.left, Vector2.right };
void OnMouseDown()
{
GetAllAdjacentTiles();
}
private GameObject GetAdjacent(Vector2 castDir)
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, castDir);
if (hit.collider != null)
{
print(hit.collider.gameObject.name);
return hit.collider.gameObject;
}
return null;
}
private List<GameObject> GetAllAdjacentTiles()
{
List<GameObject> adjacentTiles = new List<GameObject>();
for (int i = 0; i < adjacentDirections.Length; i++)
{
adjacentTiles.Add(GetAdjacent(adjacentDirections[i]));
}
return adjacentTiles;
}
}
I have tried to use the code above to detect tiles in all 4 directions but when I click on a tile I just get the name of the tile that was clicked.
Each tile has the Tile Script and a BoxCollider2D attached, why is it not printing all 4 tiles surrounding the current tile?

By default for Physics2D you are hitting your own collider the Raycast starts in.
To solve this go to the Physics2D Settings via Edit &rightarrow; Project Settings &rightarrow; Physics2D and disable the option
Queries Start In Colliders
Enable this option if you want physics queries that start inside a Collider 2D to detect the collider they start in.

Related

How Can I Not Make Points Spawn In The Same Place Twice? (Unity)

guys so I'm trying to make an endless Map Generator for my 2D grappling Hook Game Kinda like Danis square Game and I was trying to generate a set number of swingable points in certain range to test.
Everything works fine except that some Points overlap each other when spawned So I was wondering how could I prevent this from happening?
Should I change my code or is there any method of spawning things I should try so they don't overlap?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MapGenerator : MonoBehaviour
{
public Transform Endpositin;
public int NumOfSwwingablePoints;
public GameObject SwinggablePoint;
public int MinX, MaxX;
public int MinY, MaxY;
public int Xpos;
public int Ypos;
Vector2 PointPos;
void Start()
{
for (int i = 0; i <= NumOfSwwingablePoints; i++)
{
Xpos = Random.Range(MinX, MaxX);
Ypos = Random.Range(MinY, MaxY);
PointPos = new Vector2(Xpos, Ypos);
Instantiate(SwinggablePoint, PointPos, Quaternion.identity);
}
}
// Update is called once per frame
void Update()
{
}
}
I have Tried this Method and I have also tried to increase values and giving the points colliders to see if they overlap but none of that works. I have also tried update function, but they just keep spawning, and it never stops
My suggestion is everytime you create a new block then save the position of the block in a list.
when next time you create a new block, check the new position with the list.
Here is the code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MapGenerator : MonoBehaviour
{
public Transform Endpositin;
public int NumOfSwwingablePoints;
public GameObject SwinggablePoint;
public int MinX, MaxX;
public int MinY, MaxY;
private int Xpos;
private int Ypos; // this can be private since we use only privatly
Vector2 PointPos;
List<Vector2> PointPosList = new List<Vector2>();
void Start()
{
for (int i = 0; i < NumOfSwwingablePoints; i++) // I change <= to < since we start from 0
{
Generating();
}
}
void Generating()
{
bool foundSamePosition;
do
{
foundSamePosition = false;
Xpos = Random.Range(MinX, MaxX);
Ypos = Random.Range(MinY, MaxY);
PointPos = new Vector2(Xpos, Ypos);
// finding the generated position is already exist
for (int i = 0; i < PointPosList.Count; i++)
{
if (SamePosition(PointPos, PointPosList[i]))
{
foundSamePosition = true;
}
}
} while (foundSamePosition);// if we found the position try again
// if not found, add the new position to a list for next time check
PointPosList.Add(PointPos);
Instantiate(SwinggablePoint, PointPos, Quaternion.identity);
}
private bool SamePosition(Vector2 v1, Vector2 v2)
{
return (v1.x == v2.x && v1.y == v2.y);
}
}

Unity 2D - Change the sprite by script DOESN'T WORK

I have multiple images then push them into "Sprite[] sprites".
I create a gameobjectPrefab and add Rigidbody2d + Box Colider 2d + SpriteRenderer.
I want to Instantiate number of gameobjectPrefabs equal to the number of other sprites.
But it doesn't work, plz teach me the problem. The Sprites don't change:
public Sprite[] sprites;
public GameObject diamondPrefab;
void Start()
{
CreateDiamondsListSprites();
}
void CreateDiamondsListSprites()
{
for (int i = 0; i < sprites.Length; i++)
{
var go = diamondPrefab;
go.GetComponent<SpriteRenderer>().sprite = sprites[i];
listAllDiamondsFromSpritesList.Add(go);
// Here is sample : i add to list<gameOject> to use later
Instantiate(listAllDiamondsFromSpritesList[index],listLocationPoint[index]);
}
}
Set the sprite on the instantiated gameObject, after instantiation
void CreateDiamondsListSprites()
{
for (int i = 0; i < sprites.Length; i++)
{
var go = Instantiate(diamondPrefab,listLocationPoint[index]);
go.GetComponent<SpriteRenderer>().sprite = sprites[i];
listAllDiamondsFromSpritesList.Add(go);
}
}

Curve and stretch a sprite to mouse click/touch

I wish to create a game object where you can start dragging it by touching somewhere on the line of its collision and to create these "dynamic shapes" by stretching the sprites and readjusting the sprite look and collision according to the drag point.
Adding an illustration for clearance:
Started playing with Sprite Shape Renderer to create these curved sprite tiles but I need to be able to create dynamic ones using the mouse cursor and adjust all collisions.
I've tried to add an AnchorDragger script to the Sprite Shape Renderer object:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.U2D;
public class AnchorDragger : MonoBehaviour
{
const int INVALLID_INSERTED_POINT_INDEX = -1;
public SpriteShapeController spriteShapeController;
private Spline spline;
private int inseretedPointIndex = INVALLID_INSERTED_POINT_INDEX;
void Start()
{
spline = spriteShapeController.spline;
int pointCount = spline.GetPointCount();
for (var i = 0; i < pointCount; i++)
{
Vector3 currentPointPos = spline.GetPosition(i);
Debug.Log("Point " + i + " position: " + currentPointPos);
}
}
// Update is called once per frame
void Update()
{
if (inseretedPointIndex != INVALLID_INSERTED_POINT_INDEX)
{
spline = spriteShapeController.spline;
spline.SetPosition(inseretedPointIndex, Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1.0f)));
spriteShapeController.BakeCollider();
}
}
void OnMouseDown()
{
Debug.Log("Mouse Down Position:" + Input.mousePosition);
Vector3 mouseDownPos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 1.0f));
Debug.Log("World Position: " + mouseDownPos);
spline = spriteShapeController.spline;
int pointCount = spline.GetPointCount();
int closestPointIndex = int.MaxValue;
float minDistance = int.MaxValue;
for (var i = 0; i < pointCount; i++)
{
Vector3 currentPointPos = spline.GetPosition(i);
float distance = Vector3.Distance(currentPointPos, mouseDownPos);
if (distance < minDistance)
{
minDistance = distance;
closestPointIndex = i;
}
}
spline.InsertPointAt(closestPointIndex, mouseDownPos);
spline.SetTangentMode(closestPointIndex, ShapeTangentMode.Continuous);
inseretedPointIndex = closestPointIndex;
Debug.Log("Inserted point index: " + inseretedPointIndex);
}
void OnMouseUp()
{
Debug.Log("Mouse Up");
spline = spriteShapeController.spline;
spline.RemovePointAt(inseretedPointIndex);
inseretedPointIndex = INVALLID_INSERTED_POINT_INDEX;
}
}
Basically tried to figure the closest point on the spline where I've clicked and then inserting a new point and setting its position on Update to where the mouse is and delete the point on mouse up.Right now I'm having a problem where the drag position is not correct for some reason.Where I clicked, where the new point position is set:
even when I tried to play with where I click and where I take my mouse to while dragging, not sure why, could use help!
Camera.ScreenToWorldPoint isn't appropriate here because you don't already know how far away to check from the camera, which is needed for the z position. An incorrect z component would give the nearest point on the spline to some point that the mouse is aligned with, but not on the sprite, and would modify the spline at an unexpected position:
Instead, draw a ray from the camera and see where it intersects with the plane the sprite lives on, and use that world position.
In Update:
void Update()
{
if (inseretedPointIndex != INVALLID_INSERTED_POINT_INDEX)
{
spline = spriteShapeController.spline;
Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
Plane p = new Plane(Vector3.forward,spriteShapeController.spline.GetPosition(0));
float d;
p.Raycast(r,out d);
spline.SetPosition(inseretedPointIndex, r.GetPoint(d));
spriteShapeController.BakeCollider();
}
}
In OnMouseDown:
void OnMouseDown()
{
Debug.Log("Mouse Down Position:" + Input.mousePosition);
Ray r = Camera.main.ScreenPointToRay(Input.mousePosition);
Plane p = new Plane(Vector3.forward, spriteShapeController.spline.GetPosition(0));
float d;
p.Raycast(r,out d);
Vector3 mouseDownPos = r.GetPoint(d);
Debug.Log("World Position: " + mouseDownPos);

Switching active states of two GameObjects in Unity3D

With Unity3D I am trying to create a scene with an alpha texture as a silhouette, which upon looking up is added, then looking down removes.
Currently I have the exposure of an equirectangular image changing on look up, but my silhouette object says I have not assigned it to an instance:
As you can see from the console, it is eventualy recognised, but I cannot set the active state. This is the current state of my code being applied to the scene:
using UnityEngine;
using System.Collections;
public class switchScript : MonoBehaviour {
public Cardboard cb;
public Renderer leftEyeDay;
public Renderer rightEyeDay;
private GameObject[] dayObjects;
public GameObject nightObject;
void Start () {
MeshFilter filter = GetComponent(typeof (MeshFilter)) as MeshFilter;
if (filter != null) {
Mesh mesh = filter.mesh;
Vector3[] normals = mesh.normals;
for (int i=0;i<normals.Length;i++)
normals[i] = -normals[i];
mesh.normals = normals;
for (int m=0;m<mesh.subMeshCount;m++)
{
int[] triangles = mesh.GetTriangles(m);
for (int i=0;i<triangles.Length;i+=3)
{
int temp = triangles[i + 0];
triangles[i + 0] = triangles[i + 1];
triangles[i + 1] = temp;
}
mesh.SetTriangles(triangles, m);
}
}
}
// Update is called once per frame
void Update () {
float xAngle = cb.HeadPose.Orientation.eulerAngles.x;
if (isLookingUp (xAngle)) {
var exposureValue = getExposureValue (xAngle);
leftEyeDay.material.SetFloat ("_Exposure", exposureValue);
rightEyeDay.material.SetFloat ("_Exposure", exposureValue);
toggleNight ();
} else {
leftEyeDay.material.SetFloat ("_Exposure", 1F);
rightEyeDay.material.SetFloat ("_Exposure", 1F);
toggleNight ();
}
}
public bool isLookingUp (float xAngle) {
return xAngle > 270 && xAngle < 340;
}
public float getExposureValue (float xAngle) {
var _xAngle = Mathf.Clamp (xAngle, 320, 340);
return ScaleValue (320.0F, 340.0F, 0.3F, 1.0F, _xAngle);
}
public float ScaleValue (float from1, float to1, float from2, float to2, float v) {
return from2 + (v - from1) * (to2 - from2) / (to1 - from1);
}
void toggleDay() {
print (nightObject);
nightObject = GameObject.FindGameObjectWithTag ("Night");
nightObject.SetActive (false);
}
void toggleNight() {
print (nightObject);
nightObject = GameObject.FindGameObjectWithTag ("Night");
nightObject.SetActive (true);
}
}
GameObject.FindGameObjectWithTag ("Night") returns null when the whole object is set to !active. Just toggle the scripts on that object instead of the whole GO.
Ok, if anyone needs this, this is an easy way to create scene switch:
void Awake() {
silhouetteObject = GameObject.FindGameObjectWithTag ("Night");
silhouetteObject.GetComponent<Renderer>().enabled = false;
}

Unity Roguelike Project: Argument Out of Range Exception

I'm getting an Argument Out of Range Exception for this script I'm following in a Unity tutorial.
Here's the exception:
ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index
System.Collections.Generic.List`1[UnityEngine.Vector3].get_Item (Int32 index) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/Dictionary.cs:225)
BoardManager.RandomPosition () (at Assets/Scripts/BoardManager.cs:75)
And here's the actual script for the project:
using UnityEngine;
using System; //Allows serializable attribute, which modifies how variables appear
using System.Collections.Generic; //Generic allows use of lists
using Random = UnityEngine.Random; //Used because Random class is in both System and Unity engine namespaces
public class BoardManager : MonoBehaviour
{
[Serializable]
public class Count
{
public int maximum;
public int minimum;
public Count (int min, int max) //Assignment constructor for Count to set values of min, max when we declare a new Count
{
minimum = min;
maximum = max;
}
}
public int columns = 8; //8x8 gameboard
public int rows = 8;
public Count wallCount = new Count(5, 9); //Specifies random range for walls to spawn in each level
public Count foodCount = new Count(1, 5); //Random range for food spawns
public GameObject exit; //Variable that holds exit prefab
public GameObject[] floorTiles; //Game Object Arrays hold our different prefabs to choose between
public GameObject[] wallTiles;
public GameObject[] foodTiles;
public GameObject[] enemyTiles;
public GameObject[] outerWallTiles;
private Transform boardHolder; //Manages Hierarchy
private List<Vector3> gridPositions = new List<Vector3>(); //Declares a private list of Vector3s
//Tracks all possible positions on gameboard, and keeps track of whether object has been spawned in that position or not
void InitialiseList()
{
gridPositions.Clear();
for (int x = 1; x < columns - 1; x++) //Nested FOR loops to fill list with each of the positions on our gameboard as a Vector3
{
for (int y = 1; y < rows - 1; y++)
{
gridPositions.Add(new Vector3(x, y, 0f)); //Adds x and y positions to the list
}
}
}
void BoardSetup() //Sets up outer wall and floor of gameboard
{
boardHolder = new GameObject("Board").transform;
for (int x = -1; x < columns + 1; x++)
{
for (int y = -1; y < rows + 1; y++)
{
GameObject toInstantiate = floorTiles[Random.Range(0, floorTiles.Length)]; //Defines a new GameObject
if (x == -1 || x == columns || y == -1 || y == rows)
{
toInstantiate = outerWallTiles[Random.Range(0, outerWallTiles.Length)];
}
GameObject instance = Instantiate(toInstantiate, new Vector3(x, y, 0f), Quaternion.identity) as GameObject;
//Instantiates a new GameObject. Rotation is always the same. Used as GameObject.
instance.transform.SetParent(boardHolder);
}
}
}
Vector3 RandomPosition()
{
try
{
int randomIndex = Random.Range(0, gridPositions.Count);
Vector3 randomPosition = gridPositions[randomIndex]; //THROWING AN EXCEPTION
gridPositions.RemoveAt(randomIndex); //Prevents duplicate position spawns
return randomPosition;
}
catch (Exception ex1)
{
Debug.Log(ex1);
throw;
}
}
void LayoutObjectAtRandom(GameObject[] tileArray, int minimum, int maximum)
{
int objectCount = Random.Range(minimum, maximum + 1);
for (int i = 0; i < objectCount; objectCount++)
{
Vector3 randomPosition = RandomPosition();
GameObject tileChoice = tileArray[Random.Range(0, tileArray.Length)];
Instantiate(tileChoice, randomPosition, Quaternion.identity);
}
}
public void SetupScene(int level) //Called by the GameManager
{
BoardSetup();
InitialiseList();
LayoutObjectAtRandom(wallTiles, wallCount.minimum, wallCount.maximum);
LayoutObjectAtRandom(foodTiles, foodCount.minimum, foodCount.maximum);
int enemyCount = (int)Mathf.Log(level, 2f); //Scales enemy count based on level
LayoutObjectAtRandom(enemyTiles, enemyCount, enemyCount);
Instantiate(exit, new Vector3(columns - 1, rows - 1, 0f), Quaternion.identity);
}
}
I'm assuming that the RandomPositions() function is throwing the exception, though I am unable to find a problem with the code. Does anyone see the problem?