Collision Detection of objects in certain area of camera in Unity3d - unity3d

I am creating a 3rd person action game where the player is a helicopter and he can shoot other objects while moving. The problem is I am trying to find the enemy objects who are inside a circle in the center of the camera and I need to track them and shoot them.
Raycast wouldn't help as i need a thicker raycast and so I tried spherecast and capsulecast.
I have a GUI element which gives the player idea on where he can shoot.When using Spherecast or Capsulecast, It is working when the enemy is near but when the enemy is far behind I guess the spherecast becomes small while traveling along z and doesn't hit the object most times.
if (Physics.SphereCast (startPoint, 1f, transform.forward, out hit)) {
if (hit.collider.CompareTag ("Shootable") ){
Debug.Log(hit.collider.name);
Destroy(hit.collider.gameObject);
}
}
I have seen raycast from camera and so i was wondering if there is something to do like circlecast from the camera which would be appropriate for this. If not how can I proceed?
Any help is really appreciated.

If you want to detect whether enemies lie within a conical area in front of your camera, using a SphereCast or RayCast will not be able to meet your needs.
Instead, you might consider checking the angle between an enemy's relative position and your camera's forward vector, to see if it is below a particular value, and hence within the cone.
For a 60-degree field of view, and assuming you store your enemy Transform components in an array/List, your code might look like:
foreach (Transform enemy in enemies){
if (Vector3.Angle(transform.forward, enemy.position - transform.position) < 30){
Destroy(enemy.gameObject);
}
}
Hope this helps! Let me know if you have any questions. (Answer adapted from this Unity question.)

Related

Why does the object get stuck in the wall when repelled?

I made the endless movement of the object and its repulsion from the walls, but it does not always work correctly. At rounded corners (sometimes even at a straight wall), it just gets stuck and stops moving altogether, or moves slowly to the point where it stops moving. What can this be related to and how can it be fixed?
private void FixedUpdate() {
rb.velocity = direction * normalSpeed;
lastDirection = direction;
}
private void OnCollisionEnter2D(Collision2D collision) {
//Repulsion from objects.
direction = Vector3.Reflect(lastDirection.normalized, collision.GetContact(0).normal);
}
There is a small distance between the objects, but the circle seems to stick to the wall and moves with it until it collides with another collider:
Example
there are objects under the circle that also have colliders, but the collision between them is not considered, since they have the same layer (in the settings, I disabled the collision for objects on the same layer). What can be done to fix this error and what can it be related to?
The object in the general scale:
Example
I tried to increase the size of the wall collider, tried to change polygon collider to box collider, connect composite collider, changed the mechanics of the object movement (in these cases, the movement could work incorrectly), but the result was always the same - the jams (sticking to the wall) continued.
It is difficult to answer your question without having more information, but I can suggest if you are using physics to move your objects - utilize physic materials and remove code that changes direction manually in OnCollisionEnter. Using physic materials you can easily make your object bounce from colliders of your choice without losing velocity.

How move object with collision (without physics) Unity

I have 3d cube which have 3d box collider.
I want to write jump system for cube with collision, but without physics (without gravity, without rotation, etc) (Like 3d platformer)
You can take advantage of the Physics.OverlapBox API to check for collisions before committing to move your object.
Your code will look something like this:
Vector3 nextPosition = transform.position;
/*
You do your normal movement code, but apply
it to nextPosition instead of transform.position
*/
Collider[] hitColliders = Physics.OverlapBox(nextPosition, transform.localScale/2);
if(hitColliders.Length == 0){
transform.position = nextPosition;
}
Note that the object itself shouldn't have a collider, otherwise it will detect itself. You also shouldn't move in big steps as this method doesn't take colliders on the path into account.
There is a great way of doing this. You will still need physics.
The Steps
Have a rigidbody on your player.
There should be a dropdown menu called spmethiing like "constraints". Find it.
Then Set all rotation constraints in this menu to true.
However, I don't understand why you wouldn't want gravity. Don't all platformers have gravity? (There must be some force to pull your player down when they jump). Anyways, if you don't want gravity, then you must uncheck Use Gravity variable.
**Notes: **
To control your player, you must use AddForce(). If you have any questions about adding force, let me know in the comments.
:) Thanks.

Get all hit objects between two moving points?

I want to set transparent all trees which are between player and camera, my game is top down, and vector between camera and player changes. So, how to Raycast between two points and also get all objects that are hit by ray? I know there is Linecast for raycast between two points, but it returns only first object and RaycastAll on the other hand can be casted only in specific direction... Any idea how to cast ray between player and camera and get all hit objects?
Although Physics.RaycastAll() doesn't appear to immediately meet your needs, you can easily adapt it to give you what you want.
If you perform a raycast from the player in the direction of the camera, and limit it to only the distance between the player and the camera, then you effectively only cast a ray between the two positions and will only get object between them.
Here's how I suggest you approach it:
float distToCamera = Vector3.Distance(camera.transform.position, player.transform.position);
Vector3 dirToCamera = camera.transform.position - player.transform.position;
RaycastHit[] hits;
hits = Physics.RaycastAll(player.transform.position, dirToCamera, distToCamera);
Hope this helps! Let me know if you have any questions.
A quick search and look at this and use it on your trees and when they became visible to the camera and after that do what ever you want with objects
note : this event can be fire with any camera rendering those objects so beware of which camera you are using to render trees is right

How to calculate the length of platform/object in Unity 5?

I'm new to Unity and after watching and reading some tutorials I'm now trying to make a simple 2D platformer kind of game. In the said game both enemies and player can jump to different platforms and traverse it like the old SnowBros game.
The problem I'm facing is related to programming the enemy movement. In my game there would be several types of enemies but generally for now there are two types, one that can jump from the platform and one that only walks upto the length of the platform, wait for 1 second then flip and walk backwards; meaning they don't get off the platform. Now this is an issue I'm having trouble with. I can't seem to find a way to calculate the length of the underlying current platform. I thought of using the collider.bound.min.x and max.x to come around the problem but the issue is I can't seem to find a simple way to reach the current platform's collider without fetching the script and then going through it.
Since, there would be many platforms of many different sizes and each platform is made up of a prefab of other platforms, it just doesn't seem like a workable solution to use the platform script and then traverse through it.
You can use Physics2D.Raycast to "sense" for collisions on a Ray. Imagine the enemy putting their toe one step forward, feeling if there is still solid ground, and then deciding whether to stop.
void Update()
{
Vector2 newPosition = transform.position + velocity * Time.deltaTime;
Vector2 downwardDirection = Vector2.down; // you may have to replace this with your downward direction if you have a different one
RaycastHit2D hit = Physics2D.Raycast(newPosition, downwardDirection);
if (hit.collider != null)
{
// solid ground detected
transform.position = newPosition;
}
else
{
// no ground detected. Do something else...
}
}
You can and should define the Layers your Raycast is supposed to hit, so it can ignore the enemy itself and avoid self-collision.
Well, I hope that you have prefabs of platform and in those prefabs put colliders at start and at end. You can specify layers and tags so that only enemy can detect those colliders and then you can detect tags on collision from enemy script and make your operation.
First create layers by opening Edit -> Project Settings -> Tags and Layers. Create two Layers
Create layers for enemy and enemyColliders and Goto Edit -> Project Settings -> Physics2D. Set collision matrix as EnemyCollider will collider with enemy only.
And your prefab will be looks like,
I hope this would help you.

Destroy an enemy with spotlight

function OnCollisionEnter(theCollision : Collision)
{
if(theCollision.gameObject.name=="Spotlight")
{
Destroy(gameObject);
Debug.Log("Dead");
dead = true;
}
}
This is my code here, I have a spotlight attached to my enemy which acts like a torch, what I want is for the enemies to be destroyed once they walk into the spotlight.
I tested the collider with the player and it works fine but for some reason, when I set it to the spotlight, nothing happens at all.
Can anyone help me out here?
You can ray cast from the origin of the light to your surface. Once you have found the intersection point of this ray with your surface you can control the XZ position of a capsule or sphere collider of size(radius, N, radius) - attach your detection script to that collider and you'll be able to work with it as if it were a physical object in the scene.