Ive been trying to use raycasting for the better part of a day now to remove 2D objects . I know how to use the OnMouseDown method to effectivelly do the same thing and ive been using it so far. But ive read that using raycastign is much more efficient then using the OnMOuseDown method since the OnMouseDOwn method was designed specifically for mouse clicks. Looking over tutorials aswell as reading the forums ive seen people using different raycasting techniques, classes and methods available in the Unity libraries but these are mostly used for 3D objects. Since I'm designing a 2D game I want to find out how to do it for 2D objects. Ive tried severl things in order to get it to work but nothign seems to work:
Ive tried using Raycasthit2D, Raycast2D and nothing seems to work
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TouchTest : MonoBehaviour
{
void Start()
{
}
//public Vector2 direction;
void Update()
{
//Cast a ray in the direction specified in the inspector.
RaycastHit2D hit =
Physics2D.Raycast(this.gameObject.transform.position,
Input.GetTouch(0).position);
//If something was hit.
if (hit.collider != null)
{
//Display the point in world space where the ray hit the collider's surface.
Debug.Log("We Hit something");
}
}
}
The result should be that it outputs "we hit something" on the console when I touch an object on Unity Remote but it doesn't do anything except saying that my index for Input.GetTouch(0).position is out of bounce. Despite the fact that it says this it often says this but for other code, it still manages to perform what I want, but for this code, it doesn't work and still says the index is out of bounce.
The error you are receiving is because when the function is being called, the mouse is not clicked.
You must do this in the OnMouseDown method or put it in an if statement that only allows it to run if the mouse is actually clicked.
A good tutorial on this can be found here.
The best way (if you are only using 2D) is to check if the mouse click is in the shape when it is cliked:
Check when the mouse is clicked and get its position.
Get the rectangle of the body and compare it to the mouse position.
If the body's rectangle contains the mouse position, the mouse has clicked the body.
Related
I'm fairly new to Unity and I've decided to work on a simple 2d platformer from youtube tutorials.
Everything works fine until I start using collisions. My problem isn't only that it doesn't work, It's that it doesn't appear at all on auto-complete.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class finishLine : MonoBehaviour
{
void Start()
{
}
void Update()
{
}
private void OnCollisionEnter2D(Collision2D col) {
if (col.gameObject.CompareTag("Player")) {
SceneManager.LoadScene("level2");
}
}
}
I've also added rigid bodies and box colliders to both objects (player and finish line).
Anyone know what's wrong?
Make sure that you used BoxCollider2D and not the 3D one.
If the autocomplete doesn't work try restarting VisualStudio or whatever IDE you use. If that doesn't work look in the Unity Settings under External Tools and try regenerating project files. That works for me sometimes.
So a couple things you might want to look into to fix this are:
Check if you have the right colliders on both your gameobjects (in this exmaple box collider 2D I assume)
Check if either of your colliders has the "Is Trigger" box check or not. If yes then uncheck it
Make sure your player gameobject has the "Player" tag and the same as the tag you compare in your script because compare tag is case sentitive
Check if you have your finishLine script on the object you want as the root object meaning it's the parent of all the other one inside it and has no parent (this doesn't need to be the case all the time but in this scenario it might help fix the problem)
Did you check the trigger box in the colliders?
Does any one of those objects have a rigid body?
Did you have other functions that destroyed the character when it reaches the destination that is meant to be the trigger?
You can try to set up a two new cubes for testing purposes to narrow down the problem.
I'm trying to understand how to get the closest to a destination with Unity's navigation system when a Nav Mesh Obstacle is in the way.
I have this example with a Capsule obstacle (with Carve on) and a capsule agent managed with a script. It seems to work okish, but when I "click" on the obstacle to set the destination of the agent (to a point inside the carved area), the agent moves to another location around the obstacle.
How can I make the agent go to the closest point around the obstacle or to the closest point to the selected destination (that is inside the area of the obstacle)?
Script to move the agent
using UnityEngine;
using UnityEngine.AI;
public class CapsuleMovement : MonoBehaviour {
NavMeshAgent agent;
public NavMeshPathStatus partial;
void Start() {
agent = GetComponent<NavMeshAgent>();
}
void Update() {
if (Input.GetMouseButtonDown(0)) {
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100)) {
agent.destination = hit.point;
}
}
}
}
Take the center of the clicked objects position and move it slightly towards the moving unit/player, then use that position as your coordinate instead of the direct mouse click.
If that doesn't work.
This is not a guaranteed answer as that is hard to give in a situation such as this, but I hope this brings you further.
I suspect that it may be the coordinate you click, which something is not working out as it should with. Try spawn a "ClickObject" which can just be a coloured sphere, at the position of the mouse click. That way you can confirm where the click actually is happening.
Here is furthermore 2 methods that may come in handy when working with NavMeshes and positioning.
You could try use SamplePosition.
https://docs.unity3d.com/540/Documentation/ScriptReference/NavMesh.SamplePosition.html
Finds the closest point on NavMesh within specified range.
Perhaps also FindClosestEdge
https://docs.unity3d.com/530/Documentation/ScriptReference/NavMesh.FindClosestEdge.html
Locate the closest NavMesh edge from a point on the NavMesh.
I'm trying to make a character selection screen similar to that of something like Super Smash Bros. and using a controller, but I'm having trouble doing so. Currently this is what I have for to try to accomplish this
if (Input.GetKeyDown(KeyCode.Joystick1Button1))
{
RaycastHit rayInfo;
Ray ray = Camera.main.ScreenPointToRay(transform.position);
if (Physics.Raycast(ray, out rayInfo))
{
Debug.Log("raycast hit");
rayInfo.collider.gameObject.SendMessage("Selected");
}
}
But from what I can tell it doesn't seem to me like the ray cast is hitting anything due to the fact that the debug.log never runs despite being directly over the icon/character I would like to select. How can I fix this and make it work?
Firstly, the screen point that you're using to do the ray collision is transform.position. Unless this script is attached to a game object that already follows the mouse somehow, you probably want that to be the mouse position.
Secondly, you should check to make sure that there is a collider on the object that you're trying to raycast into.
Thirdly, if the selection screen is 2d, you can get away with:
Collider2D hitInfo =Physics2D.OverlapPoint(Camera.main.ScreenToWorldPoint(Input.mousePosition));
if (hitInfo.gameObject!=null){
//Do selection logic here.
}
I am working on multiplayer collaboration in Unity3d using Smartfox Server2x.
But I wish to change it in to a hide and seek game.
When the hider (third person controller) presses the button "seek me" the seeker tries to find the hider. But I don't know How can I identify when a seeker sees the hider. Is it possible using Raycasting. If yes how? Please help me.
void Update () {
RaycastHit hit;
if(Physics.Raycast(transform.position,transform.forward,out hit,50))
{
if(hit.collider.gameObject.name=="Deccan Peninsula1")
{
Debug.Log("detect.................");
}
if(hit.collider.gameObject.tag =="Tree")
{
Debug.Log("detect.........cube........");
//Destroy(gameObject);
}
}
From Unity Answers by duck:
There's a whole slew of ways to achieve this, depending on the precise
functionality you need.
You can get events when an object is visible within a certain camera,
and when it enters or leaves, using these functions:
OnWillRenderObject, Renderer.isVisible,
Renderer.OnBecameVisible, and OnBecameInvisible
Or you can calculate whether an object's bounding box falls within the
camera's view frustum, using these two functions:
GeometryUtility.CalculateFrustumPlanes
GeometryUtility.TestPlanesAABB
If you've already determined that the object is within the camera's
view frustum, you could cast a ray from the camera to the object in
question, to see whether there are any objects blocking its view.
Physics.Raycast
You could do many things to find out if a seeker has found the hider. I am going to suggest how I would do it and I will try to make the idea/code as efficient as possible.
Each GameObject knows its position via the transform component. You can check how close one object is from the other by creating a ratio and comparing how close they are from each other. The moment both objects are close to each other then you enter a new state. In this state you will fire a RayCast only when the direction/angle of view of the seeker changes. So think of it this way, your seeker is looking around and as he is spinning he is firing the RayCast. The main idea is not to fire way too many RayCasts all the time which will hinder performance. Make sure your RayCast ignores everything except who you are looking for.
If you get stuck you can ask a more specific question, probably regarding RayCast and how to make them ignore walls or not shoot through walls, or maybe you discover that solution on your own.
Good luck!
Tried to find this kind of problem around the net but failed so...
Here's the thing - I have a prefab gameobject that is to represent a unit, portrait more specifically. It has several scripts attached and an Animation component with two animations: Static and Selected.
The prefab is instantiated, moved freely and, after placing, it can be clicked to select it, which should, aside from executing a bit of code, start the Selected animation.
Using this code:
void OnMouseDown(){
//
//Some inside stuff
//
if (this.GetComponent<UnitHandling> ().thisUnit.Selected)
this.animation.Play("Selected");
if(this.animation.IsPlaying ("Selected"))
Debug.Log("Animation of selection is playing");
}
I checked that the animation seems to be playing (at least the Debug message is showing) but I see no animation... What am I doing wrong?
Try making an animation state using mechanim, and play it using this:
GetComponent<Animator>().CrossFade("Selected", 0);
https://docs.unity3d.com/Documentation/ScriptReference/Animator.CrossFade.html
https://docs.unity3d.com/Documentation/Manual/MecanimAnimationSystem.html