Problems with detecting collision for a character selection screen - c#

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.
}

Related

Removing 2D objects on touch using Raycasting?

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.

Raycast based movement has weird interaction with colliders

I'm using a character controller, which moves the character along a set path using ray casting:
This works fine for moving by x and z axis, and I'm also able to land on objects if I hit them directly from top. But if I enter an object with a collider from the side, either pass through or get stuck:
I assume this happens because the player is set to position itself along the raycast, and to avoid the player to teleport up on the platforms, I need the raycast to ignore them. Now this causes the new collision problem. Does anyone have any idea on how to work around this, so my player properly is colliding with the platforms? I'm using all physics inside a FixedUpdate(), and the path is created using the Tween plug-in, but I assume this issue would appear with any script using raycast in this manner.
Add specific mask to those platforms, and in code where you calling ray cast, just add new variable for mask and there just don't select the platform mask.

Get touch input for touchscreen devices like androidPhone in unity?

I'm trying to make a game using unity and at this point I have created a cube object, a ground object a couple other things. I can make it move by giving it a forward force. I'm basically trying to make a game about a cube that you can navigate through obstacles.
What I want to know is how to get the input like touch input. For example you would use getkey("d") If you wanted to get input from "d" in the keyboard. How would I do the same except for touch input in android?
Use this
Input.GetMouseButtonDown(0)
Example
if(Input.GetMouseButtonDown(0)){
circle.velocity = Vector2.up * jumpForce;
}
https://docs.unity3d.com/ScriptReference/Input.GetTouch.html
You can use this to get a touch object which will give you the screen position, then you can use your cameras position and angle to cast a ray from that point to see if the user is touching the cube.

Why does my raycast sometimes does detect a hit and sometimes wont?

I have a bullet that is fired with a Impuls on the rigidbody.
Then, each frame i do a raycast forward with the speed of the bullet, which sometimes does, and sometimes doesn't find an enemy.
When i skip through the game frame by frame, i can clearly see my debug-raycast inside the (boc)collider of the enemy, but it still won't find it.
Im pretty sure it doesn't just pass the enemy, in the editor i can clearly see the green raycast inside the collider.
Any suggestions? I also tried with a linecast, which i found on here, but that gives the same result. (the line is on the exact same position and also draws the debug-line inside the collider. The layers are also correct, as i said, sometimes it will, and sometimes it wont find the target...
void Update()
{
//get direction and distance
Vector3 direction = _rigidBody.velocity.normalized;
float distance = (_rigidBody.velocity.magnitude * Time.deltaTime);
//raycast for targets
RaycastHit raycast;
if (Physics.Raycast(transform.position, direction, out raycast, distance, HitLayerMask))
{
Debug.DrawRay(transform.position, direction, Color.red);
}
else
{
Debug.DrawRay(transform.position, direction, Color.green);
}
}
You can see the tiny debug ray, aswell als the collider from side-view. It also it almost right in the middle from the front-view.
I'm thinking it might be because the start and end of the raycast are inside the boxcollider?
the rigidbody is moved by
//Speed = 500 in this case, but lowering doesn't change anything
rigidBody.AddRelativeForce(Vector3.forward * Speed, ForceMode.Impulse);
UPDATE:
After some more debugging and testing, i found that it happens because you won't get a hit from inside a collider.
Here's what happend:
bullet is outside target collider, but raycast is to short to find it.
bullet moves forward, enemy also moves forward (closing in on eachother). Bullet is now inside the collider
raycast won't find enemy because thats just how raycast work
What i could do, is make the distance of the raycast further, but also not so far away that it would result in weird hits that would graphically look weird.
i thought that using
float distance = (_rigidBody.velocity.magnitude * Time.deltaTime);
would be enough (since thats the distance the bullet traveled since last frame, but because the enemy also moves, the above can happen. Well, it would be enough if the enemy wouldn't move :/
One possible solution is to go to Project Settings -> Script execution order and put the bullet's MonoBehavior after Default Time. That way everything else has already finished moving before you do the ray cast. A hacky solution but should work.

Create ability radius Unity C#

I'm developing a unity game's ability system in which some of the spells have specific range, I'm not quite sure how to do that but here's what i camed up with.
I will need some sort of sphere which will be invisible and the center of it will be my character.
The radius of the sphere will be equal to the range of the spell selected.
My spells are being cast over the mouse position which means i will be able to check if the sphere is colliding with the mouse.
Overall this idea with the sphere seems good to me because later on i will be able to add color to it so the user can also see the phsycal range of the spell if he want's to. But i see a few problems :
The mouse is moving only in 2 dimension x and y however for a 2D object collission to be detected the method requires another 2D colider, well the sphere is 3D.
private void OnTriggerEnter2D(Collider2D other)
{
}
I'm not sure how to make let's say 500 pixels range to be still relative to my screen and therefore this to be the actual radius of the sphere because my characters dont seem to move huge distance when i'm looking at the x axis, they move just a tiny bit and making a sphere with radius of 500 on the x axis will be complete disaster.
As i said I'm not sure how to make this, I'm new to unity and i'm not sure how to implement my idea, so any help or tips are welcome.
You need to project your mouse in 3D to do the collision check. (You can imagine your mouse shooting a line right in front of it) You can do that using raycast:
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if ( Physics.Raycast (ray,out hit,100.0f))
{
if(hit.collider == yourSphereCollider)
{
// the mouse was pointing at the sphere
}
}
Note that if there is another collider between the sphere and the mouse, it will be detected instead.
You can also use the same technique to determine where on the ground your effect should be displayed

Categories

Resources