I’m making a small shooter for two players, everyone can shoot. The problem is that when a bullet flies at high speed, then there are certain zones in its trajectory in which it does not touch the object, and accordingly OnTriggerEnter2d does not work there. Here is the bullet flight script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet: MonoBehaviour
{
Rigidbody2d rb;
public int Player;
public float speed = 0.4f;
public Vector3 mode; // Direction of the bullet (Vector3.left, right)
// Start is called before the first frame update
void Start ()
{
rb = gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void FixedUpdate ()
{
rb.velocity = mode * speed;
}
}
High speed physics is always a hard nut to crack. Like Iggy mentions you can/should use continuous collision detection.
If you still have issues and still want fast projectiles it get harder. Here are some options.
You can lower the physics time step in time settings (very expensive not recommended but you can test).
You can make the bullet's colliders dynamically bigger. (Might be the simplest easiest solution). When you spawn bullets, calculate based on their speed how long a box collider should be and dynamically position it behind the bullet sorta like a trail (make sure the bullet has moved forward enough to fully expand so you don't hit things behind the player). The box collider's size should be the same as how much distance it moves every frame. That way after moving a tons in a frame all the positions the bullet has been in the frame will trigger a collision on the box collider. For bullet impact and sfx don't spawn them where the bullet is but at the point of contact.
You can calculate if a collision should have happened. (After the physics update check behind the projectile with like a raycast).
You can do your own physics or hybrid. Unity lets you simulate physics when ever you want manually instead of the normal physics update. With more control over that you could add more calculations for fast moving object.
Related
First, I know that this question has been asked a lot, but I cant find a solution, so mi problem is, Im making an educational game, and I have a vein and the blood flow (with many box colliders) and a single blood cell (also with a box collider) however i want the cell to destroy when it reaches the wall collider, but it doesn't it just stays there, here is the project!
http://tinypic.com/r/10706es/9
(cant upload images because of my reputation, sorry)
The collider where I want to destroy my cell is the pink collider, however when it touches it it just does nothing, here's my script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class collision : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void OnCollisionEnter(Collision col)
{
print("hihi");
if (col.gameObject.tag == "Collider")
{
Destroy(gameObject);
}
}
}
Also, here is the AddForce script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AddForce : MonoBehaviour {
public float thrust;
public Rigidbody rb;
private Vector3 up;
private bool move;
void Start()
{
rb = GetComponent<Rigidbody>();
up = new Vector3(0, 1, 0);
move = false;
}
void FixedUpdate()
{
if (Input.GetKey("space"))
{
if (rb.velocity.magnitude < 5)
rb.AddForce(up * thrust);
move = true;
}
else
{
if (move == true)
rb.velocity = new Vector3(0, -0.5F, 0);
}
}
}
thanks for your help guys! :D
It can be several things, whether you are using OnTriggerEnter or OnCollisionEnter:
Missing RigidBody (the most common). At least one of the GameObjects involved needs to have a RigidBody. (check if at least one of them have a RigidBody attached and, if you are using OnCollisionEnter, does not have the "Is Kinematic" checked). See the below collision matrix for more information.
Missing tag. The GameObject from collision does not have a "Collider" tag (try to remove the if statement to test it) (to compare tags, use collider.gameObject.CompareTag("Collider"), it has a better performance)
Undetectable collision. The physics Layer Collision Matrix is set to not detect collision between the layers the objects are (enter Edit > Project > Phisics and check if the encounter of the layer of both GameObjects are checked inside Layer Collision Matrix)
Wrong Collider configuration. one or both of the GameObjects have a small/wrong placed or absent Collider (check if they both have a Collider component and if their size are correct)
If it's working, you should be able to press play and drag one GameObject into the other one and your Debug.Log will appear.
As an advice, use tag names that better describe the group of GameObjects that will be part of it, like "RedCells" or "WhiteCells". It'll be easier to configure the Layer Collision Matrix and improve the performance of your game.
Another advice: for colliders that just destroys another GameObject (don't react, like bump or actually collide) I use triggers. That way, the collision between them will not alter anything in the remaining GameObject (like direction/velocity/etc). To do that, check the Is Trigger in the Collider and use OnTriggerEnter instead of OnCollisionEnter.
Source
some times you added Nav Mesh Agent component to your game object ( to auto route operation in strategic game and ...).
in this case, this game object does not attend to collider.
So, if you really need this Nav Mesh Agent, you should add Nav Mesh Obstacle to other fixed game object and also add Nav Mesh Agent to other movable game object.
I have a few followup questions which might lead to a solution.
First, does the object holding your 'collision' script have a rigidbody and a collider on it?
Second, does the wall have both a rigidbody and collider?
Usually if those conditions are met, then collisions will work.
A couple other things that could be the problem:
Check if you have istrigger checked for either object and make sure it is unchecked.
Check and make sure the rigidbodies on both are non-kinematic.
I've finally fixed it, I dont really know if this was the problem, but i just removed the rigidbody from the parent of the wall and it started working!, I dont know what the rigidbody did, but just with that the problem was fixed, thank you all for your help! :D
Ensure the following things are considered in your code,
All gameobject should contain collider attached and the player
gameobject should contain the rigidbody component in it.
The collider size should change to the width and height of the
component instead of default (1,1) values.
I would like to use a characters tongue so instead of shooting a bullet, it goes toward the enemy, licks it, and comes back. I got this wording from this question: Unity shooting with Tongue 2d game (hasn't been answered and is 4+ years old). The only difference is my character moves.
I have this code from looking at a shooting tutorial so when you click the tongue prefab generates and is at the correct angle. I need it to grow on click and shrink back.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LineController : MonoBehaviour
{
public GameObject player;
private Vector3 target;
public GameObject crosshairs;
public GameObject tonguePrefab;
// Start is called before the first frame update
void Start()
{
Cursor.visible = false;
}
// Update is called once per frame
void Update()
{
target = transform.GetComponent<Camera>().ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, transform.position.z));
crosshairs.transform.position = new Vector2(target.x, target.y);
Vector3 difference = target - player.transform.position;
float rotationZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
if (Input.GetMouseButtonDown(0))
{
shootTongue(rotationZ);
}
}
IEnumerator shootTongue(float rotationZ)
{
GameObject t = Instantiate(tonguePrefab) as GameObject;
t.transform.position = new Vector2(target.x, target.y);
t.transform.rotation = Quaternion.Euler(0.0f, 0.0f, rotationZ);
yield return new WaitForSeconds(2000);
t.SetActive(false);
}
}
I was also trying to make it disappear after whatever time and with that it doesn't work at all?
If the prefab is just a line with a simple texture I suggest using a line renderer:
Create an empty transform that starts on the mouth and then it move untill it reaches the crosshair. The movement is done using Vector2.MoveTowards.
Your tongue will no be a line renderer component. This line renderer will have 2 points, the start which is static, and the end which you have to update on the Update() for example, to correspond to the positions of the empty transform in item 1.
If you really wish to expand a tongue gameobject instead, then you are going to need a bit of math, this answer has what you need but in 3D:
https://answers.unity.com/questions/473076/scaling-in-the-forward-direction.html
1) I suggest creating sprite/sprite sheet animations with Mecanim or relatively new Skeletal Animation with Anima2D. With these systems you can create nice animations, transitions, even animate the sphere collider to trigger collisions and actions, change active state of your objects, etc. and control the animation with very little code. This way you can get best effects in my opinion.
As tongue is not a bullet... :) You only need one. I don't think you want to Instantiate/Create prefabs every time you press the lick button. Instead you should just turn your tongue object on/off (gameObject.SetActive). You can also change your object active state within the animation. So if you don't know how to code it you can do most of it in the Animation window and use very simple code to play the animation when you press the lick button. Whenever a sphere collider touches something you can tell the Animator Controller to play a 'roll back' animation and it will transition nicely to the start position.
There are many tutorials about Mecanim, Animations, 2D Animations, Anima2D, Animator Controller out there.
2) If you need very good control over the tongue you could create a custom mesh and control it via script but this is far more difficult.
3) The reason why your object is not turning off is probably because you wrote WaitForSeconds(2000) so it will turn off after 2000 seconds - more than half an hour. You should also call it with StartCoroutine(shootTongue()) as it is a Coroutine. Again if you want to turn off the object don't create new ones every time. If you want to keep creating new objects you should Destroy the objects instead. Otherwise you will end up with a lot of deactivated tongues in your scene and I don't think you needs that many tongues.
I'm trying my first test-game with Unity, and struggling to get my bullets to move.
I have a prefab called "Bullet", with a RigidBody component, with these properties:
Mass: 1
Drag: 0
Angular drag: 0,1
Use grav: 0
Is Kinematic: 0
Interpolate: None
Coll. Detection: Discrete
On the bullet prefab, I have this script:
public float thrust = 10;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
rb.AddForce(transform.forward * 100, ForceMode.Impulse);
}
On my playerController script (not the best place for this, I know):
if (Input.GetAxisRaw("Fire1") > 0)
{
var proj = Instantiate(projectile, transform.position, Quaternion.identity);
}
When I click my mouse, the bullet gets created, but doesn't move. I've added velocity to the rigidbody, which works, but I can't get it to move in the right direction. After googling around, it seems I need to be using rigidBody.AddForce(), which I did, but still can't get my bullet to move.
I've seen the other solution, but this did not work for me either.
Any advice would be appreciated.
Screenshot:
When you're working with 2D in Unity, the main camera basically becomes an orthographic camera (no perspective effects) looking sideways at the game scene along the z-axis. Incidentally, the "forward" direction of a non-rotated object is also parallel to the z-axis.
This means that when you apply a force along transform.forward, you're sending the object down the z-axis - which will not be visible to an orthographic camera looking in the same direction. The quick fix here would be to use a direction that translates to an x/y-axis movement, like transform.up or transform.right.
As derHugo also mentioned in the comments, you might want to look into using Rigidbody2D. There are some optimizations that will allow it to behave better for a 2D game (though you may not notice them until you scale up the number of objects).
First, I know that this question has been asked a lot, but I cant find a solution, so mi problem is, Im making an educational game, and I have a vein and the blood flow (with many box colliders) and a single blood cell (also with a box collider) however i want the cell to destroy when it reaches the wall collider, but it doesn't it just stays there, here is the project!
http://tinypic.com/r/10706es/9
(cant upload images because of my reputation, sorry)
The collider where I want to destroy my cell is the pink collider, however when it touches it it just does nothing, here's my script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class collision : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void OnCollisionEnter(Collision col)
{
print("hihi");
if (col.gameObject.tag == "Collider")
{
Destroy(gameObject);
}
}
}
Also, here is the AddForce script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AddForce : MonoBehaviour {
public float thrust;
public Rigidbody rb;
private Vector3 up;
private bool move;
void Start()
{
rb = GetComponent<Rigidbody>();
up = new Vector3(0, 1, 0);
move = false;
}
void FixedUpdate()
{
if (Input.GetKey("space"))
{
if (rb.velocity.magnitude < 5)
rb.AddForce(up * thrust);
move = true;
}
else
{
if (move == true)
rb.velocity = new Vector3(0, -0.5F, 0);
}
}
}
thanks for your help guys! :D
It can be several things, whether you are using OnTriggerEnter or OnCollisionEnter:
Missing RigidBody (the most common). At least one of the GameObjects involved needs to have a RigidBody. (check if at least one of them have a RigidBody attached and, if you are using OnCollisionEnter, does not have the "Is Kinematic" checked). See the below collision matrix for more information.
Missing tag. The GameObject from collision does not have a "Collider" tag (try to remove the if statement to test it) (to compare tags, use collider.gameObject.CompareTag("Collider"), it has a better performance)
Undetectable collision. The physics Layer Collision Matrix is set to not detect collision between the layers the objects are (enter Edit > Project > Phisics and check if the encounter of the layer of both GameObjects are checked inside Layer Collision Matrix)
Wrong Collider configuration. one or both of the GameObjects have a small/wrong placed or absent Collider (check if they both have a Collider component and if their size are correct)
If it's working, you should be able to press play and drag one GameObject into the other one and your Debug.Log will appear.
As an advice, use tag names that better describe the group of GameObjects that will be part of it, like "RedCells" or "WhiteCells". It'll be easier to configure the Layer Collision Matrix and improve the performance of your game.
Another advice: for colliders that just destroys another GameObject (don't react, like bump or actually collide) I use triggers. That way, the collision between them will not alter anything in the remaining GameObject (like direction/velocity/etc). To do that, check the Is Trigger in the Collider and use OnTriggerEnter instead of OnCollisionEnter.
Source
some times you added Nav Mesh Agent component to your game object ( to auto route operation in strategic game and ...).
in this case, this game object does not attend to collider.
So, if you really need this Nav Mesh Agent, you should add Nav Mesh Obstacle to other fixed game object and also add Nav Mesh Agent to other movable game object.
I have a few followup questions which might lead to a solution.
First, does the object holding your 'collision' script have a rigidbody and a collider on it?
Second, does the wall have both a rigidbody and collider?
Usually if those conditions are met, then collisions will work.
A couple other things that could be the problem:
Check if you have istrigger checked for either object and make sure it is unchecked.
Check and make sure the rigidbodies on both are non-kinematic.
I've finally fixed it, I dont really know if this was the problem, but i just removed the rigidbody from the parent of the wall and it started working!, I dont know what the rigidbody did, but just with that the problem was fixed, thank you all for your help! :D
Ensure the following things are considered in your code,
All gameobject should contain collider attached and the player
gameobject should contain the rigidbody component in it.
The collider size should change to the width and height of the
component instead of default (1,1) values.
I am working on a breakout style game in Unity using c# and wanted to know what is the best way to increase the speed of the ball over time without changing the angle/direction the ball travels after colliding with the paddle, so I want the ball to travel in the same direction/angle (say 45 degrees).
To start with I am using the simple code below which is attached to a box collider on the left of the paddle to get the ball to move left as desired. This gets the angle right but I wanted to increase the speed over time but not sure how to.
void OnCollisionEnter2D(Collision2D col) {
if (col.gameObject.tag == "ball") {
col.gameObject.GetComponent<Rigidbody2D> ().velocity = new Vector2 (-10f, col.gameObject.transform.position.y);
}
}
I simply forgot to try the most basic solution which is to multiply the Vector by a speed variable, duh!. This does the intended behaviour I was after.
col.rigidbody.velocity = new Vector2 (-10f, col.gameObject.transform.position.y) * speed;