my unity gravity isn't functioning properly, how do I fix it? - c#

I'm new to this, I'm making an obstacle dodging game, and part of the losing conditions is that if the player object falls below -1 on the y axis then the player loses the game, but every time I run the game and intentionally go off the edge of the ground, the player object just floats. I've double checked that the Rigidbody for the player uses gravity, and even checked my scripts for logic errors, nothing has worked. got any ideas on how to fix it?
I've already added the code rb.useGravity = true;
here's the script for the player's movement:
`
using UnityEngine;
public class movement : MonoBehaviour
{
public Rigidbody rb;
public float ForwardMomentum = 1000f
public float SidewaysMomentum = 500f
void FixedUpdate()
{
rb.useGravity = true;
rb.AddForce(0, 0, FowardMomentum * Time.deltaTime);
if (Input.GetKey("d"))
{
rb.AddForce(SidewaysMomentum * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
else if (Input.GetKey("a"))
{
rb.AddForce(-SidewaysMomentum * Time.deltaTime, 0, 0, ForceMode.VelocityChange);
}
}
To make a reproducible example for this, all you need to do is:
Add a cube game object (I believe that the box collider and mesh renderer should already be loaded in there)
Add the Rigidbody component and tick use gravity (As well as ticking freeze rotation on the x axis)
Add the new script with the code from above (please fix any errors you find to make it work and let me know how you did it :D)
Add a ground floor and just make it so the player cube is sitting on top of it
then just run it a couple of times and see how it goes, if nothing is out of the ordinary then idk what's going on with my unity

In unity using Rigidbodies is sometimes a bit difficult. But the solutions to these problems come pretty easily.
-Firstly Check if you even have applied a rigidbody (mostlikely you do else your game wouldn't run)
-Check if you have accidently selected "IsKinematic" which could cause your gravity not to be used on that rigidbody.
-Check the way you get the rigidbody in your script, if the script is correctly applied to your gameobject. (if the rigidbody is gotten via the inspector you might need to just drag and drop it into the script)
-Check the collider on your ground if it isn't bigger then the visual

Related

Unity attach Object to other Object

I am trying to attach an Projectile to the Player if he gets hit.
Im currently using this code:
transform.SetParent(player.transform);
But this doesn't work as expected.
It seems to follow only movement caused by the Player-Object and not its Rigidbody mean the Projectile will follow this:
transform.position -= transform.right * Time.deltaTime * moveSpeed;
But not this:
rb.AddForce(transform.up * forceMult); or Gravity
So I need a way to make the Projectile also follow the movement caused through the Rigidbody.
Anybody know a way to do this?
To move the arrow and the player via. RigidBody isn't possible from just parenting, because
regarding moving of objects parenting only helps with changing the transform of children if the transform of parent objects changed.
Therefore you should probably get the Arrow Rigidbody and move it via. rb.AddForce() as well.
In public Variables of Player add:
Rigidbody rbArrow;
When you parented the arrow to the player call this function from the player:
transform.SetParent(player.transform);
player.GetArrowRB();
New Function in the Player:
public static void GetArrowRB(){
rbArrow = GetComponentInChildren<RigidBody>();
}
Movement Code:
// Move Player
rb.AddForce(transform.up * forceMult);
// Move Arrow
rbArrow.AddForce(transform.up * forceMult);

Bullet not moving

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

Moving a GameObject using tags not working Unity

I know this is quite the noob question, but whatever, there's only one way to learn.
I've created an empty GameObject in Unity, attached a script that is supposed to move a cube(my player) and gave my cube the tag "Player". After creating the cube, I was hoping to be able to move the cube without having to put the script on the cube itself. When the script is on the cube, it moves without a problem (I know this is how it probably should be done, but for trying to learn new things I wanted to do it this way).
Player Controller script
Cube properties
After failing to find the answer through Google, any insight at all is greatly appreciated!
Thank you
Update!
Here's the code as text now, since it was asked for.
public class GameCoreController : MonoBehaviour {
private GameObject PlayerMove;
public Rigidbody rb;
void Start ()
{
PlayerMove = GameObject.FindGameObjectWithTag("Player");
rb = GetComponent<Rigidbody>();
}
void Update()
{
// character movement
if (Input.GetKey(KeyCode.W))
{
PlayerMove.transform.Translate(0, 0, 0.25f);
}
if (Input.GetKey(KeyCode.S))
{
PlayerMove.transform.Translate(0, 0, -0.25f);
}
if (Input.GetKey(KeyCode.A))
{
PlayerMove.transform.Translate(-0.25f, 0, 0);
}
if (Input.GetKey(KeyCode.D))
{
PlayerMove.transform.Translate(0.25f, 0, -0);
}
}
I've updated the code from before to include PlayerMove.transform.Translate but I still have the same issue with the cube note moving. I've also included screenshots of my scene with the cube and the GameCoreController; the empty GameObject holding the script that is supposed to control the cube.
Thanks again for the help guys.
Update 2!
After deleting the cube and re-insert it into the scene it now moves. Thanks for the help everyone.
The reason that the cube won't move because in your code you didn't move its transform but you move the transform of the gameobject that you attached this script to.
transform.Translate move the transform of the gameobject that this script attach to. So if you want to move the cube, all you need to do is change from transform.Translate to PlayerMove.transform.Translate which will move the transform of PlayerMove gameobject which is your cube with "Player" tag on it
^ All of the above. Plus, in the screenshot, your rigidbody is not set to "is kinomatic". This means that physics will still be applied to it (like gravity). Rule of thumb: If you have a moving object where collision is important, it will need a rigidbody and a collider. If the object is not moved with physics commands (eg rigidbody.AddForce()) but rather manipulating the transform as you are, set the rigidbody "isKinomatic" property to true.

Collision detection not working unity

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.

Unity rigidbody FixedUpdate basic movement does not work

I'm trying to implement this tutorial on the unity site. I've went over the unity blog and havn't found the solution to my problem there.
I have a simple Rigidbody sphere object over a plane.
The sphere is default sized, and set on: (0,0.5,0).
The plane is also default sized, and set on the origin (0,0,0). Those are the only components I use.
What I'm trying to do is to write a simple C# script behavior for the sphere that will move it across the plane, like so:
public class Controller : MonoBehaviour {
private Rigidbody rb; // Holds the body this script is affecting.
// Called at the start, to set variables.
void Start()
{
rb = GetComponent<Rigidbody>(); // Get the body, if there is one.
}
//For physical changes.
void FixedUpdate()
{
float Horizontal = Input.GetAxis ("Horizontal"); // Get horizontal movement from input.
float Vertical = Input.GetAxis ("Vertical"); // Get vertical movement from input.
Vector3 Movement = new Vector3 (Horizontal, 0.0f, Vertical); // Declaring the movement I'd like to add to the RB. Y axis is irrelevant. X,Z - controlled by user input.
rb.AddForce (Movement); // Making the movement.
}
}
I attached this behavior to the sphere, expecting It'd move when I hit some input key.
Despite this, when I play the project, everything compiles fairly well but the sphere just doesn't move regardless of what I type.
What am I missing?
EDIT: If it's relevant, I also have problems opening the Unity c# code editor (forgot it's name). Whhenever I click open, it just instantly closes. I do everything on Visual Studio.
EDIT 2: My bad, I just figured out I have console Errors. I get the following one:
MissingComponentException: There is no 'Rigidbody' attached to the "Player" game object, but a script is trying to access it.
You probably need to add a Rigidbody to the game object "Player". Or your script needs to check if the component is attached before using it.
UnityEngine.Rigidbody.AddForce (Vector3 force) (at C:/buildslave/unity/build/artifacts/generated/common/modules/NewDynamics.gen.cs:706)
Controller.FixedUpdate () (at Assets/_Scripts/Controller.cs:20)
"Player" is the name I gave the sphere.
I forgot to attach the Rigidbody to the sphere.

Categories