My character just jumps continuously even in the air, I'm not sure why the boolean does not stop it and I cannot figure it out. This is what I have so far:
using UnityEngine;
public class PlayerCollision : MonoBehaviour
{
public Rigidbody rb;
bool spacePressed = false;
float upForce = 200f;
void OnCollisionEnter(Collision collisionInfo)
{
if (collisionInfo.collider.tag == "Obstacle")
{
spacePressed = false;
}
}
void Update()
{
if (Input.GetKey("space") && spacePressed == false)
{
spacePressed = true;
rb.AddForce(0, upForce * Time.deltaTime, 0, ForceMode.VelocityChange);
}
}
}
My guess is that 'space pressed' is never or instantly set to false. So a first step on debuging it can be to watch the boolean. You can do that with 'public ...'. Then you should just observe when it's set to true/false.
There is also the possiblilty of this being a totally different kind of issue. For instance that one of the colliders could be of the wrong size (too big/small)
And to complete the holy trinity: There is a free 2D platformer example in the unity hub. I think they use a different approche by using an empty GO as a 'isGrounded' checker. One of the first things I learned as a hobbist is not to be ashamed to copy code of example projects.
Good luck.
It is likely that the collider is hitting Obstacle as it makes its first jump. OnCollisionEnter is very unreliable when checking if an object is beside/on another object. This can be checked if you use Debug.Log and check to see how much times it randomly activates OnCollisionEnter.
To reliably check if an object is beside another object use raycasts or boxcasts instead.
This is some code that should work that uses raycasts:
using UnityEngine;
public class PlayerCollision : MonoBehaviour
{
public Rigidbody rb;
public Collider collider;
public float extraCheckHeight = 0.1f;
float upForce = 200f;
bool isGrounded(){
Physics2D.Raycast(collider.bounds.center, Vector3.down, collider.bounds.extents.y + extraCheckHeight);
}
void Update()
{
if (Input.GetKey("space") && isGrounded)
{
rb.AddForce(0, upForce, 0, ForceMode.VelocityChange);//Time.deltaTime is should not be here because it should be the same force regardless of the time between frames
}
}
}
This should do the trick but I recommend researching about unity raycasts and boxcasts.
Here is a video on Ground Checking that I found useful when I was approached with a similar problem: Ground Check
Related
im trying to make it so that if my character continues to touch a gameobject with a damage script the player continuesly gets damaged. instead of this result i only get damaged once when touching the gameobject. there are no error messages. ive tried to replace the if with a while loop and it ended up crashing my game. is there any way to loop a if statement preferably with a way to time it.
if (other.tag == "Player")
{
healthScript.healthPoints -= damage;
}
this is the if statement im trying to loop.
First, I am under the assumption you are using Colliders as triggers with the Is Trigger attribute selected. I am also assuming this is a 2D game. If not, this same approach will work, you will just have to change the methods from 2D to 3D.
You will want to add the OnTriggerEnter2D() and OnTriggerExit2D() methods to your player health script. These will allow us to detect when the player is standing on the damaging object. From here, we will start a coroutine which can be used to deal damage in a timed manner.
using System.Collections;
using UnityEngine;
public class HealthScript : MonoBehaviour
{
public float healthPoints = 100f;
public float damage = 5f;
public bool OnDamagingObject = false;
IEnumerator DealDamage()
{
while (OnDamagingObject)
{
healthPoints -= damage;
yield return new WaitForSeconds(1f);
}
}
void OnTriggerEnter2D(Collider2D hitInfo)
{
GameObject collider = hitInfo.gameObject;
if (collider.tag == "DamagingObject")
{
OnDamagingObject = true;
StartCoroutine(DealDamage());
}
}
void OnTriggerExit2D(Collider2D hitInfo)
{
GameObject collider = hitInfo.gameObject;
if (collider.tag == "DamagingObject")
{
OnDamagingObject = false;
}
}
}
For those who wish to use OnTriggerStay(), I will also provide a solution for that. This time, we will keep the script on the damaging object, following the structure the question asker is using.
using UnityEngine;
public class DamageScript : MonoBehaviour
{
public HealthScript healthScript;
public float damage = 5f;
void OnTriggerStay2D(Collider2D hitInfo)
{
GameObject other = hitInfo.gameObject;
if (other.CompareTag("Player"))
{
healthScript.healthPoints -= damage;
}
}
}
As mentioned in the comments of my other answer, implementing both OnTriggerEnter() and OnTriggerExit() allow more control over dealing damage to the player. One of the downsides to using OnTriggerStay() is I am unsure how to deal the damage in a timed manner. Additionally, OnTriggerStay() limits how you can deal damage to the player. If in the future you wanted to give 5 damage to the player when they first touch the damaging object but 2 damage for every second thereafter while touching it, it is not possible to do so using OnTriggerStay().
I'm making a game in Unity VR in which I punch numbers and get points.
The gloves are responsible for detecting collisions between the numbers that they hit. On my gloves I have a PunchScript component and the numbers each have a rigidBody and collider.
The problem is that no collisions seem to ever occur. I placed a Debug.LogError inside of the collision detection code to assert this.
I tried switching on/off kinematics on all objects and used different collision systems to no avail.
Here's my PunchScript component:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PunchScript : MonoBehaviour
{
public SteamVR_TrackedObject hand;
private Rigidbody rBody;
private bool visible = true;
// Start is called before the first frame update
void Start()
{
rBody = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
rBody.MovePosition(hand.transform.position);
rBody.MoveRotation(hand.transform.rotation);
// print(rBody.velocity.magnitude* 1000);
}
void OnCollisonEnter(Collision other)
{
Rigidbody otherR = other.gameObject.GetComponentInChildren<Rigidbody>();
if (other.gameObject.name == "frpnchbg") {
Debug.LogError("Hit!");
}
if (other == null)
return;
Vector3 avgPoint = Vector3.zero;
foreach (ContactPoint p in other.contacts) {
avgPoint += p.point;
}
avgPoint /= other.contacts.Length;
Vector3 dir = (avgPoint - transform.position).normalized;
otherR.AddForceAtPosition(dir *50f* rBody.velocity.magnitude, avgPoint);
}
}
Here's how the glove object looks in the Unity inspector.
It is very important to write the name of Unity callback methods correctly, otherwise Unity will not be able to detect them on the object (and as a result, can never execute them).
In your case, you have misspelled the OnCollisionEnter callback.
Instead of OnCollisonEnter it should be OnCollisionEnter.
I want to create a jumping Script, i got so far, the problem is that i do not want the gameObject to jump midair
I tried using OnCollisionStay/Enter together with OnCollisionExit to generate a bool which gets checked together with Input before jumping, this worked the best but unity is missing triggers
I cant check for position with gameObject.transform.position.y because i have differently elevated platforms.
isGrounded works with a different code but it interferes with my other movements (which are implemented by AddForce on Input)
I can't wrap my head around why this code doesn't work, i hope someone can help me understand.
using UnityEngine
public class PlayerMovement : MonoBehaviour
{
private CharacterController controller;
public Rigidbody rb;
public Transform PPos;
public float jumpForce = 10f;
}
public void Update()
{
if(controller.isGrounded && Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(0, jumpForce, 0);
Debug.Log("Jump Executed");
}
}
I don't get a Syntax Error
Edit
You need to set the controller.isGrounded whenever your character has the ability to jump.
PlayerScript
void OnCollisionEnter(collision other)
{
controller.isGrounded = other.gameObject.CompareTag("Ground");
}
Original
If you want to jump in mid-air, you're going to have to remove the condition that your character controller is on the ground.
if(Input.GetKeyDown(KeyCode.Space))
I have this C# script attached to my main camera game object which also has a capsule collider attribute. However, it doesn't seem to do anything. How should I modify/add to this to make the camera "jump" and fall down to the ground again?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Jump : MonoBehaviour {
[HideInInspector] public bool jump = false;
public float jumpForce = 1000f;
public Transform groundCheck;
private bool grounded = false;
private Rigidbody rb;
// Use this for initialization
void Awake ()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update ()
{
grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
if (Input.GetButtonDown("Jump") && grounded)
{
jump = true;
}
}
void FixedUpdate()
{
if (jump)
{
rb.AddForce(new Vector2(0f, jumpForce));
jump = false;
}
}
}
Also, I would like to have the key for this be the spacebar if possible, but whatever key works or is there already is fine. I am still learning C#, so please forgive me if the solution is obvious.
This line is most likely causing the problem:
grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));`
There are 2 reason that it wont produce proper results:
You haven't setup your ground tiles or the place where you character moves to the "Ground" layer. You wont have this by default but you can add it from the Project Settings->Tags and Layers menu.
Your colliders are not close enough to the ground thus not causing collision.
Besides that it should work fine.
I have a cannon that fires a bullet in a parabolic arc. Right now when I fire the bullet stays in the same rotation as it was when it fired out of the cannon.
How do I make it so the bullet's rotation follows the arc as it travels through the air?
I tried the following as a script running on the bullet
Exhibit 1
public class PointingBehaviour:MonoBehaviour
{
private Rigidbody rb;
private void Awake()
{
rb = GetComponent<Rigidbody>();
}
public void Update()
{
transform.up = rb.velocity;
}
}
And that works fairly well. but I see a slight flicker on the first frame the object exists (I think this is because the velocity is still 0 at this point) and the object spins uncontrollably once it hits the ground.
I got it to stop flickering at the start and stop spinning when it lands by doing the following
public class BulletController : MonoBehaviour
{
private Rigidbody _rb;
private bool _followArc;
private bool _firstFrame;
private void Start()
{
_rb = GetComponent<Rigidbody>();
_firstFrame = true;
_followArc = true;
}
public void LateUpdate()
{
if (_followArc && !_firstFrame)
transform.up = _rb.velocity;
_firstFrame = false;
}
public void OnCollisionEnter(Collision collision)
{
_followArc = false;
}
}
But if I happen to bump something in the air it stops following the arc and just does a free tumble till it lands. What is the "Correct" way to do what I want to do?
Because people wanted to see it, here is the code for spawning the bullet.
public class TankController : MonoBehaviour
{
private Transform _barrelPivot;
private Transform _bulletSpawn;
public GameObject Bullet;
public float FirePower;
public float RotationSpeed;
public float TiltSpeed;
private void Start()
{
_barrelPivot = GetComponentsInChildren<Transform>().First(x => x.CompareTag("BarrelPivotPoint"));
_bulletSpawn = GetComponentsInChildren<Transform>().First(x => x.CompareTag("BulletSpawn"));
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
FireCannon();
}
//(SNIP) Handle turning left and right and pivoting up and down.
}
private void FireCannon()
{
var newBullet = SpawnBullet();
var rb = newBullet.GetComponent<Rigidbody>();
rb.AddForce(_bulletSpawn.up * FirePower, ForceMode.Impulse);
}
private GameObject SpawnBullet()
{
var newBullet = (GameObject) Instantiate(Bullet, _bulletSpawn.position, _bulletSpawn.rotation);
newBullet.transform.localScale = Bullet.transform.localScale;
return newBullet;
}
}
I believe what you're saying is - your're script exhibit1 works great.
If you think about it, all you have to do is turn off that behavior, when you want to.
In this case, you're thinking "that behavior should stop when it hits the ground .. I assume that's what you mean physically.
It's very easy to turn off a MonoBehaviour, as you know just enabled = false;
So, you have some script somewhere like Bullet or perhaps BulletBoss
In there you'll have a variable private PointingBehaviour pb and you'll just pb.enabled = false
(I can't tell you "when" you want to do that, it depends on your game .. so it might be something like "when altitude is less than blah" or "when I hit something" ... probably OnCollisionEnter related.)
Note that - I'm sure you know this - for pointing behavior for a projectile, just setting it along the tangent is pretty basic.
A lovely very easy thing to do when you're writing a pointing behavior for a projectile like that, try lerping it gently to the tangent. The result is amazing real looking. Next perhaps add some random "wiggles" which is very bomb-like. It's amazing how the user can see such things, only only a few frames. (The next step up would be real air physics I guess!)
Note that, certainly, PointingBehaviour should just be its own script. You must keep behaviors totally isolated.
Regarding LateUpdate mentioned, there is never a need to use it.
Unity offer a "script order execution" system (see Preferences menu option), if one truly wants to order within the frame. But about the only reason to do that would be perhaps for some experimentation reason.
It's rather like "using a global" - there's just no reason for it. As with any code, if you have to do something in a given order, just call in order.