Unity3d c# weapon method - c#

I am trying to create a tongue like weapon that fires from the player and then retracts back bringing back any enemies it touches. I was looking at linecast or using a mesh.
Any advice for what my work best?
The game is 3d with the player stationary in the scene and enemies flying around him. The idea was to use touch/mouse position to decide where the tongue would fire too but the 3d to 2d is causing all sorts of issues.
Any advice of where to start greatly received, I think trying two or three different approaches has left me a little bit muddled. Inspiration needed!

Here's what you'll want to do, or something to help you get started.
First you have to know exactly what you're doing to detect contact. This can be used with a trigger event with some sort of trigger box of the object.
void OnTriggerEnter (Collider object)
{
// The collision code here. Just keep reading,
}
Now it comes down to bringing the object back. You can easily just use object.gameObject.transform.position and set a new position. However this will cause the object to "jump" because you're modifying the coordinates of the object directly. So if you don't care to much about that..here's something in full you could do. This can hopefully get you started.
void OnTriggerEnter (Collider object)
{
if(object.tag == "enemy")
{
object.transform.position = new Vector3(0,0,0);
}
}
This is an example of something you could do.
Side note: You may need to change object. to object.gameObject..
I hope I've helped you enough to get you started. :)

Related

OnTriggerEnter2D working only when the game starts, i want it to check for collisions every frame

I am working on a game in unity, a type of sliding number puzzle where you have to line up each piece in ascending order. My code of checking collisions is only working when I start the game, so if I move a piece, it won't tell the near pieces that I moved the near piece. I hope you understood my problem, every help is appreciated. Thank you.
This is how my code looks with the up check. I
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.name == "Piece" || collision.gameObject.name == "Up_Collider")
{
piece_Script.Collide_Up = true;
Debug.LogError("Up");
}
else
{
piece_Script.Collide_Up = false;
}
}
I Thought that the else statement will solve this problem but it didn't.
Make sure all the things I write below are correct in your project:
1- You are using "2D" colliders on both objects.
2- At least 1 of the objects has a "Rigidbody2D".
3- IsTrigger Checkbox is active in your collider.
4- You are using the correct Tag.
5- Check layer collision matrix in - Edit > Project Setting > Physics2D.
And it is better to use tag instead of name
Based on your code in your question and your video, I see at least a couple issues.
First, there's an issue with how you're moving pieces. Your movement code for a Piece is:
Piece.transform.position = Vector3.Lerp(a, b, t);
This is not correct if you want to trigger collider events. These require interactions with rigidbodies, which means you should instead be changing the position of the piece's rigidbody with Rigidbody2D.MovePosition(). This will move your rigidbody within the physics system, which means taking into account collisions/triggers.
So (assuming you get the rigidbody for each Piece when you initialize them), your code might look like:
// Note also that I used Vector2 here - it's best you keep it consistent
pieceRigidbody.MovePosition(Vector2.Lerp(a, b, t));
Second, OnTriggerEnter2D() is not fired when two colliders stop touching. So I don't see your "else" condition being particularly useful. To achieve that with your current code, you could theoretically introduce OnTriggerExit2D() to take care of the "else" condition. However, you run into complications because while moving, a Piece may Enter and Exit the same directional colliders of two other Pieces before coming to rest. You'd have to take into account the order that occurs to get an accurate final state.
While workable, I have an alternative approach to suggest: Abandon using Trigger Collider events, and only check for a valid move at the time a Piece is clicked. Eliminate the collider event handlers, and just execute a Physics2D.OverlapBox() in each position around a Piece when it is clicked. If the position is occupied by another piece or an edge, that's not a valid move. If there is a position without something blocking it, then move the piece there.

Trouble with RigidBody

I am making a fps in unity and a game mechanic that I am trying to get is wall running/jumping
I have watched many tutorials but they cant fix the trouble I am having. To understand the code I need to explain the wall run. Basically what happens is that I have an empty game object
that raycast the left and the right of the player detecting for a wall. if it finds a wall and I'm holding left or right button (depending on what side the wall is on) it will add a force pushing the player towards the wall and another force pushing me forward. if I jump of the wall it will add a force depending on where I jumped. to make sure it was working I made a bool Value called iswallrunning but its never been set to true. can I get help with this
Code: https://github.com/ZeeScratcher/Project-robot-game/blob/main/WALLRUN.cs
Looking from the code:
you should only write code into the methods which they are responsible for. In StartWR() do not call StopWR(). This will be done in CheckForWR().
I don't know where Orientation comes from. I suppose this is from a child game object. This is fine, for a test replace Orientation by transform.
You can visualize the rays with Debug.DrawLine().
Better apply the physical force from the event FixedUpdate() instead of Update().
It is safer and more performant to cache with GetComponent() in the Awake or Start method instead of Update. If you are next to a wall in the first frame you will get a null pointer error otherwise.
Check if your walls match your given physical LayerMask and the walls have colliders.
If it is easier for you write all code into the Update() method and split it later into methods.
It would be nice to upvote my message, so I can finally make comments in Stackoverflow.
Kind Regards,
Chris

How to allow an object to move within a collider?

I am trying to have a block that can only be pushed inside of a rectangular collider. The player has to be able to move through the collider in order to push the block. I have tried to affect the mass upon the block being pushed into the edge collider, the drag, the angular drag, the velocity, isKinematic but nothing will stop the cube from moving when it hits the collider. It is really confusing, any help would really be appreciated...Here is the code:
public class pushBlock2 : MonoBehaviour {
public Rigidbody2D pBlock2;
void OnTriggerEnter2D(Collider2D col)
{
if (col.tag == "edge") {
Debug.Log ("pushblock2 touched edge");
pBlock2.isKinematic = true;
pBlock2.isKinematic = false;
}
}
void OnTriggerStay2D(Collider2D col)
{
if (col.tag == "edge") {
pBlock2.isKinematic = true;
}
}
Why don't you try and create four colliders around the area you want to move your block within? This way you'll have to stop the block from entering those which is much easier task than trying to prevent an item from leaving the collider.
I am pretty sure you will be able to pull this off without any code at all, you just need to setup a couple of static colliders to collide with objects on certain layer and put the cube you wanna move on that layer.
More info on Layer-based collisions can be found here: http://docs.unity3d.com/Manual/LayerBasedCollision.html
The way I understood, you're trying to use the volume defined by a collider as a delimiter for movement. I'm supposing you also desire "realistic" collisions when the object attempts to go outside said volume. That being the case, I'm afraid it is not possible.
The whole physics simulation is made by assuming some rules. Whenever two colliders intersect, the physics follows the rule that two objects should not occupy the same space (just like the real world), and thus it will try to figure out how to separate them again.
You can somewhat work around this by using a set of colliders that defines an hollow object, such as a barrel or box, but its more likely you'll turn off physics simulation for the box and roll up your own algorithm if consistent behavior is needed.
Many things in games are actually "fake" behaviors. Perhaps you can achieve what you want by faking physics or faking collisions?

How should I detect objects in close proximity for interaction?

I've been trying to make my character in Unity3d interact with objects that are in front of her. After trying multiple solutions and become more familiar with them I'm lost.
I've attempted using a trigger collider attached to & in front her, however triggers give issues depending on which object is moving. If the trigger itself is moving and causes the object to no longer be within it's bounds, OnTriggerExit is often not called. If I'm not mistaken the same problem occurs if the object within the trigger is destroyed.
If the trigger is on the object she's interacting with, then she could be facing backwards and still interact with it. The trigger on the stationary object would also have to be an area on every side of the object, so she could be adjacent to the object without actually facing it or very close.
Raycasts seem like a good solution, however they are of course very narrow. Wondering if there's anything I have missed.
Thanks for any assistance or opinions on the best option.
Since you noted that a RayCast can be a bit narrow, my suggestion is to use a Physics.SphereCast() in front of the player. Rather than checking along a line, it basically checks in a capsule-like space along the specified direction.
The method uses a fairly similar syntax to Physics.RayCast(). Here's an example usage:
Vector3 origin = transform.position;
float sphereRadius = 1.0f; // Change this as needed depending on tolerance you want
Vector3 direction = transform.forward;
RaycastHit hitInfo;
float maxCastDist = 5.0f; // Change this as needed depending on how close the object must be for interaction
if (Physics.SphereCast(origin, sphereRadius, direction, out hitInfo, maxCastDist)){
// Logic for checking whether object hit is interactable, etc using hitInfo.
}
Hope this helps! Let me know if you have any questions.
Raycast is a good solutuion but yes they are very narrow. But NOT BoxCast. You can send a box ray from a position on a direction. With setting size of box. Think it like too many parallel rays from character.
On the other hand, there is also SphereCast. You should choose which one is better for your program.
I think this solves your problem. And look this pages for references to this methods.
http://docs.unity3d.com/ScriptReference/Physics.BoxCast.html
http://docs.unity3d.com/ScriptReference/Physics.SphereCast.html

Hide and seek game and raycasting

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!

Categories

Resources