Unity - Help needed with spherical gravity? - c#

I am working on a game which has strong base on spherical gravity. But somehow my code is not working as expected. So please have a look at my code and tell me how can I make my spherical gravity work.
public class CircularGravity : MonoBehaviour {
private Rigidbody2D rigid;
[SerializeField]
Transform planet;
[SerializeField]
float acceleration = 0.81f;
// Use this for initialization
void Start () {
rigid = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
rigid.AddForce((planet.position - transform.position).normalized * acceleration);
transform.rotation = Quaternion.LookRotation(planet.position - transform.position, transform.up);
}
}
Problem elaboration. Project is 2d. it contains a circle sprite as a planet with a collider and hexagon has a player(just a prototype) with collider and rigidbody. This script is attached to the player(hexagon). According to my logic rigidbody should apply a force to the player and push it towards the planet and it should face the planet. So even if the player is on the downward side of circle it shouldnot fall instead it shall be pushed toward the planet. But all the colliders are being neglected and player is just going to strange position

First things I would check...
Make sure the origin of your sprite is actually in the center of the image. If it's in the corner the player will be pulled toward the corner.
Make sure both the planet and player have rigid bodies and colliders. Click on the collider and make sure the edge lines up with you shapes.
Make sure both the planet and the player have their z set to zero. Lock z in both rigidbodies.

Related

Box collider not registering collision on all axes from player

So I am making my first 3D video game in Unity3D. I want this player gameobject with a rigidbody and a capsule collider to have collision with the environment ie the player should not be clipping through walls. I've attached images of the player's components and properties.
The player has two colliders: the box collider, and the capsule collider. The box collider is disabled as of right now because if I activate the box collider instead of the capsule collider, there seems to be no collision. Aside from that, the current capsule collider looks like so.
(It is the one light green line through the center of the player model)
In the scene, there is a house next to the player to which the player should collide with the walls of the house instead of clipping through. The house has 3 different box colliders on 3 sides of the rectangle building shown below. There is no collider on the far side of the image.
Inspector for the box colliders on the house
It is important to note that there is no rigidbody component on the house and it is set as a static game object.
Here is a gif of the issue I am talking about with the above settings. From that gif it is visible that there is collision on the z-axis of the house(both sides) but there is absolutely nothing on the x-axis as I am able to clip through the house and move inside.
Initially I thought the fact that the radius of the main player gameobject's capsule collider is 0 could be the issue however there seems to only be collision with the radius set to 0(at least with the collision script I am using which is attached below). As a result, I increased the radius to where it encompassed the entire player object. Here is an image with the inspector properties of the collider included as well.
Here is the gif in play mode. From the gif any collision that was there before is completely removed and the player can now clip on all sides.
At the point, I thought it could be because I 3 different box colliders on the house and using only 1 would solve the issue. As a result, I changed the house's box collider to look like so:
Even with this house box collider, the player was able to clip through all sides of the house with both settings of the capsule collider(0 radius and radius that encompasses the player's body).
The box collider yielded the same results.
Here is my collision script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class collision : MonoBehaviour
{
public bool sendTriggerMessage = false;
public LayerMask layerMask = -1; //make sure we aren't in this layer
public float skinWidth = 0.1f; //probably doesn't need to be changed
private float minimumExtent;
private float partialExtent;
private float sqrMinimumExtent;
private Vector3 previousPosition;
private Rigidbody myRigidbody;
private Collider myCollider;
//initialize values
void Start()
{
myRigidbody = GetComponent<Rigidbody>();
myCollider = GetComponent<Collider>();
previousPosition = myRigidbody.position;
minimumExtent = Mathf.Min(Mathf.Min(myCollider.bounds.extents.x, myCollider.bounds.extents.y), myCollider.bounds.extents.z);
partialExtent = minimumExtent * (1.0f - skinWidth);
sqrMinimumExtent = minimumExtent * minimumExtent;
}
void FixedUpdate()
{
//have we moved more than our minimum extent?
Vector3 movementThisStep = myRigidbody.position - previousPosition;
float movementSqrMagnitude = movementThisStep.sqrMagnitude;
if (movementSqrMagnitude > sqrMinimumExtent)
{
float movementMagnitude = Mathf.Sqrt(movementSqrMagnitude);
RaycastHit hitInfo;
//check for obstructions we might have missed
if (Physics.Raycast(previousPosition, movementThisStep, out hitInfo, movementMagnitude, layerMask.value))
{
if (!hitInfo.collider)
return;
if (hitInfo.collider.isTrigger)
hitInfo.collider.SendMessage("OnTriggerEnter", myCollider);
if (!hitInfo.collider.isTrigger)
myRigidbody.position = hitInfo.point - (movementThisStep / movementMagnitude) * partialExtent;
}
}
previousPosition = myRigidbody.position;
}
}
I am using this free animation pack to animate the player.
Not sure if this is a Unity bug because the weird thing is that the collisions work for certain houses but not for others. Sometimes theres collision on all axes and sides with a single box collider and sometimes with two different box colliders and sometimes nothing works and there is only collision on one axis.
<IsKinematic>
"Controls whether physics affects the rigidbody.
If isKinematic is enabled, Forces, collisions or joints will not affect the rigidbody anymore..."
Deselect that in the RigidBody and the collider will work.

How come the Collider falls from the GameObject when a RigidBody is added?

I could really need some help with my GameObjects.
I am working on a game in which I want a pick-up Item to create a Physics Force explosion to blow away the enemies. I made a simple Bomb-Object to test this idea. I added a straightforward code, using a loop to collect all the colliders within its radius, to then addForce to these colliders. Now the code is working properly, but not all my GameObjects are reacting properly.
I looked into why this is, and I noticed that my Collider keeps falling away from the GameObject as soon as I add a RigidBody component to the object. The RigidBody is needed for the AddForce impact. When I remove the rb, the collider stays in place, but the object does not react to the Physics Force.
I added some images to illustrate what I mean:
Image of the Collider of the leaf sinking away..
Example image of objects which DO react to the AddForce.
I already tried to:
Copy/Paste all component settings from the reacting Cube and stone
Gameobjects to the Leaf Gameobject while disabling all other code
such as the c# scripts. The Collider & RB do not fall through the
floor but when Physics Force hits the Collider is blown away while
the GameObject keeps its position.
Try different GameObjects/Collider types.
Removed the water.
Play with amount of force/radius of the bomb.
Edited 'Tag' and 'Layerstyle' of GameObject.
The 'Explosion Code' is added below, however, I don't think the problem is in the code. I added the code to the Main Camera of my scene, and added a simple sphere as the 'bomb' GameObject.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Explosion : MonoBehaviour
{
public GameObject bomb; //set the position of the explosion
public float power = 10.0f;
public float radius = 10.0f;
public float upForce = 0.0f;
private void FixedUpdate()
{
if (Input.GetKeyDown("space"))
{
print("space key was pressed");
Invoke("Detonate", 1);
}
}
void Detonate()
{
Vector3 explosionPosition = bomb.transform.position; //set the position of our explosion to the position of the bomb.
Collider[] colliders = Physics.OverlapSphere(explosionPosition, radius); //collects all colliders within the radius.
foreach (Collider hit in colliders) { //for each individual collider the following code is ran.
Rigidbody rb = hit.GetComponent<Rigidbody>(); //declare'rb' rigidbody. Get rb component from each collider
if (rb != null)
{
print("BOOM!");
rb.AddExplosionForce(power, explosionPosition, radius, upForce, ForceMode.Impulse); //add force to each collider
}
}
}
}
How do I make the Rigidbody, Collider and GameObject of the leaf hold onto each other like the standard 3D object 'cube', so that I can make these blow away with the Physics Force just like the other models?
Thank you for your time, I have been trying things and looking around on the Internet for hours now but can't seem to find any solution.
What happens if you add the rigidbody in stop mode and press play? Does it move away in a similar manner? This may, and is expected to happen, if your colliders intersect with each other. As soon as you add a rigidbody, they find themselves trapped in a serious collision.
If you don't want to modify the scene, you can fiddle with the collision matrix in project settings / physics

Unity enemy move forward

I have an enemy on Unity, the enemy follows the player and when player is at a specific distance i want the enemy run X units without stopping. The idea is that the enemy run, then he gets tired and the Player can attack him from behind.
How can i make enemy run X distance forward without stopping?
How can i make enemy run X distance forward without stopping?
Depends on a lot of things, how is the movement handled in your game? is it 2D? 3D? etc. ...
If you use a character controller on your Enemy GameObject for example (in 2D)
Vector2 moveDirection = Vector2.zero;
void Update(){
CharacterController player = GetComponent<CharacterController>();
if (player.isGrounded)
{
// constantly move horizontally
moveDirection.x = valuespeed;
player.Move(moveDirection * Time.deltaTime);
}
}
This is just some basic theory. FOr 3D, you add a dimension and choose the direction by using the current forward vector or so.
As for checking the X value, what you could do is that in your Enemy class, when the "running mode" is triggered, you save the origin position and in the update, you check the distance between CurrentPosition and Origin (Vector3.Distance(......)) and as long as the distance is smaller than X, you let him run. If not, you are not in "running mode".

camera follows object when it rotates

I am trying to make a game where the camera follows the user, as they move around. I made the camera a child of the player and in the editor, the camera rotates around the player fine. When I play the game (in Unity) and rotate the player, the camera literally rotates instead of rotating around the player to keep the same regular following distance.
I use transform.Rotate() to rotate the player by the way.
In Summary:
Looking for camera that follows player in 3D game, that does not look different when the player turns.
issue is that the camera appears in the editor to rotate around the player perfectly, but not when transform.Rotate() is called on it during runtime in Unity.
All help is appreciated, tyvm for help.
I made the camera a child of the player and in the editor
Everything went down by doing this. You don't make the camera a child if you want it to follow the player.
What you do is to get the distance between the camera and the player in the Start() function. This is also called offset. In the LateUpdate() function, continuously move the camera to the Player's position, then add that offset to the camera's position. It is as simple as that.
public class CameraMover: MonoBehaviour
{
public Transform playerTransform;
public Transform mainCameraTransform = null;
private Vector3 cameraOffset = Vector3.zero;
void Start()
{
mainCameraTransform = Camera.main.transform;
//Get camera-player Transform Offset that will be used to move the camera
cameraOffset = mainCameraTransform.position - playerTransform.position;
}
void LateUpdate()
{
//Move the camera to the position of the playerTransform with the offset that was saved in the begining
mainCameraTransform.position = playerTransform.position + cameraOffset;
}
}

My camera rotates with my ball when i have ball as a parent gameobject of camera. what should i do?

I'm using my camera as a child gameobject of my ball, so when I move my ball camera comes with him. But the problem is I'm using rigidbody.addForce(), so when ball rotates the camera rotates with it, too.
So what should I do not to rotate my camera but only move it with my ball?
void FixedUpdate()
{
rigidbody.addForce(Input.getAxis("Horizontal"), 0, Input.getAxis("vertical"));
}
There are several ways to solve this, I'll list a few.
The first, if you don't care if your ball rotates or not, you can just disable the rotation on the ball. If you open the Constraints section in the rigidbody component, you can freeze the rotation so that the ball won't rotate.
Alternatively, you can write a script that keeps the camera always oriented a certain way. Depending on if you want the camera to rotate around the ball on any plane depends on the way you would implement this.
The third option, which is cleanest, is to not have the camera be a child of the ball. A minimal component to do this would look like this:
public class TargetFollow : MonoBehaviour
{
public Transform Target;
public float DistanceFromTarget;
void Update()
{
transform.position = Target.position + new Vector3(0, 0, DistanceFromTarget);
transform.LookAt(Target);
}
}
Just drag your ball into the 'Target' slot in your component. Keep in mind, this is super bare bones. You may want to add more variables to better control the direction the camera should be from the ball, or perhaps something that grabs a snapshot of the direction and distance the camera is from the ball in the Start method.

Categories

Resources