Rigidbody behaves differently when I select another gameobject in the scene - c#

This the strangest thing i ever saw, i swear! So i have a script to the player that when you click on screen the cube jumps in the direction of the arrow(the arrow rotates 360 degres).I changed some settings to the rigidbody2d to make the jump better.Now here comes the strange part,when i run the game and the player is selected in the scene or hierrachy the jump works fine,if i select something else for exemple the camera something chenges the jump,from a very good one to a very bad one,i tryed to build the project and test and is the same,the cube dosen't have the same "Jump".I think it's becouse i changed something in the rigidbody,idk.PLS HELP!!!center
P.S if u ask for the script here it is :
public void Update()
{
Lava.transform.position = new Vector2(transform.position.x, Lava.transform.position.y);//other,not important
cam.transform.position = transform.position + offset;//camera follow player
Arrow.transform.RotateAround(gameObject.transform.position, new Vector3(0, 0, 180), ArrowSpeed * Time.deltaTime); //to make the arrow rotate 360
if (Input.GetMouseButtonDown(0))
{
rb.AddForce(Arrow.transform.right * -ImpulseForce * Time.deltaTime, ForceMode2D.Impulse); //this makes the cube jump
}
//other
score = (int) transform.position.y;
ScoreUI.text = score.ToString();
}

Firstly, RotateAround method takes a normalized vector as its second parameter, such as Vector3.forward in your case.
Secondly, applying any force to a rigidbody should be done in FixedUpdate, not Update (see Rigidbody.AddForce and ForceMode)
In your case it's an impulse, and it's only called when you click, so no need to multiply by delta time.
rb.AddForce(Arrow.transform.right * -ImpulseForce, ForceMode2D.Impulse);
It may not solve all of your issues, but without further information it's tough to know. At least you wont have weird physics behaviors anymore.

Related

Issue with Player Movement Unity

I am VERY new to unity and I wrote this very basic program to move the player. This program works when there is no conditional statement on if the w key is pressed, but if you add it, the capsule is unable to move.
if (Input.GetKeyDown("w"))
{
Vector3 cameraForward = Camera.main.transform.forward;
cameraForward.y = 0;
cameraForward = cameraForward.normalized;
Vector3 moveDirection = cameraForward * speed * Time.deltaTime;
transform.position += moveDirection;
}
The only issue I can see with this is that the capsule is clipping into the plain, although I have a collider and a rigidbody on it. If you run this the capsule just does not move, at all. If it at all matters, I also have another line of code that sets the rotation of the capsule to 0, 0, 0, 0 every frame.
Input.GetKeyDown() only triggers once per key-press. Your biggest issue (there may be others) is that that will only move the player forward for a single tick. You want Input.GetKey() (Unity Docs) instead.

Does a speed of an object in unity affect Destroy()?

So I am making a small game in unity where you have to shoot the enemy. However, when I made the script for the bullet and enemy, it half worked and half didn't. Sometimes, the bullet would hit the enemy and destroy the enemy, however, sometimes, it would take multiple shots for it to work. But when I turn the speed of the bullet to 1 (the speed of the bullet was 500), the bullet always destroys the enemy. So this leads me to think that this has something to do with the speed of the bullet. Here is my script
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
Destroy(other.gameObject);
Destroy(gameObject);
Debug.Log("e");
}
For the movement of the bullet, I just used transform.Translate(Vector3.up * Time.deltaTime * speed). How can I fix this?
The problem is not that Destroy do not work with a certain speed, the problem is that with certain speed you are not triggering the "OnTriggerEnter".
This fenomenon is called "tunneling" it happens when the object goes too fast.
That provokes that in one frame the projectile is on one side of the collider, and in the next frame is on the other side of the collider, giving the sensation like a teleport, so that's the why it do not collide, cause in any frame the engine has detected the collide.
If you're having troubles with high speed stuff, try to set your rigidbody (the one that is moving) to Interpolate, or use raycasts to fake bigger projectile colliders.
In addition to Lotan's answer
I just used transform.Translate(Vector3.up * Time.deltaTime * speed)
whenever using physics you do NOT want to set anything via Transform as this bypasses the physics engine and thereby breaks collision detection etc as in your case.
You rather want to through the Rigidbody component and e.g. use Rigidbody.MovePosition
Rigidbody.MovePosition moves a Rigidbody and complies with the interpolation settings
like
private Rigidbody _rigidbody;
private void Awake()
{
_rigidbody = GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
_rigidbody.MovePosition(_rigidbody.position + _rigidbody.rotation * Vector3.up * Time.deltaTime * speed);
}
or why not simply set it only once
private void Start()
{
GetComponent<Rigidbody>().velocity = transform.up * speed;
}
Additionally you want to set the interpolation to dynamic.
A tricky way : bullet form A point to B point by one frame , so you can fake a point on a to b like
fake point: A+B/2
Point a ;
Point b ;
Update()
{
Point ab = (a+b)/2;
bullet.point = ab;
//check collider some .
bullet.point = b; // set it back.
a = b;
}
Not a good solution . but it have double hit rate.

Unity3D c# 2D Game Camera Follow is making jumps

I made an 2D endless runner game using Unity, where the Player Object moves upwards, but for the Viewer he remains on the same spot because the Camera is following him. The Following works pretty well, but the problem is that it is making small jumps every few seconds. The jumps are small and thus are not affecting the gameplay in general but they are big enough to make it seem like the game is not running smoothly.
I can't even tell whether it is the Camera that is making the jumps or the Player Object. But I think it is the Camera, because the spawning obstacles are also making jumps. What may be the issue? Am I using the right method for the Camera?
public class Player
{
float speed = 5f;
void Update()
{
transform.Translate(0, speed*Time.deltaTime, 0);
}
}
And this is the Script which is attached to the Camera:
public class CameraFollow
{
private Vector3 FollowVector;
public Transform Player;
void LadeUpdate()
{
FollowVector = Player.position - new Vector3(0, -4f, 10);
transform.position = Vector3.Lerp(transform.position, FollowVector, Time.deltaTime * 4f);
}
}
Does the jump happen every 4 seconds? I think the problem might be in your Vector3.Lerp function. It's basically a loose camera-follow, that takes 4 seconds (Time.deltaTime * 4f) to smoothly go from Point A to point B. Every 4 seconds it resets its path, hence the hop. At least that's my theory.
If you don't mind the camera rigidly following the player, I would just remove the Lerp and just set the transform.position to be the FollowVector value like so:
void LadeUpdate()
{
transform.position = Player.position - new Vector3(0, -4f, 10);
}
Try to use Vector3.MoveTowards
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, Player.position - new Vector3(0, -4f, 10f), step);

Instantiate a prefab pointing in the direction of another object

The Issue
I'm making a 2D Unity game where the main weapon of your character is a fireball gun. The idea is that a fireball will shoot out of the player's hand at the same angle the player's hand is pointing. I have 3 issues:
When I shoot the fireball, since the fireball is a RididBody, it pushes the player. This is because I've made the centre of the player's arm (the same place where the fireball shoots from) the point at which the arm rotates around the player (what is meant to be the shoulder);
To instantiate the fireball prefab on the arm, the only way I know how to do it is by using a piece of code which requires the arm to be a RigidBody. This means that the arm is affected by gravity and falls off the player on start unless I freeze the arm's y-axis movement, which means that when the player jumps, while the arm does not fall, it floats at the same y-position as where it started while moving along the x-axis; and
When the fireball is shot, the angle from which it is propelled after being shot is not the same angle as the angle of the player's arm.
Instantiating the Fireball
if (Input.GetKeyDown(KeyCode.Space))
{
pew.Play();
var fireballTransform = Instantiate(fireballPrefab); //creates a new shot sprite
fireballTransform.position = new Vector3(transform.position.x + horizMultiplier, transform.position.y, transform.position.z);
fireballTransform.rotation = orientation;
fireballTransform.transform.Rotate(0, 0, transform.rotation.z);
}
if (Input.GetKeyDown(KeyCode.D)) // moves right
{
orientation = 0;
horizMultiplier = 0.08F;
}
if (Input.GetKeyDown(KeyCode.A)) // moves left
{
orientation = 180;
horizMultiplier = -0.08F;
}
This piece of code is located within the script applied to the player's arm. The movement of the arm works fine and the problem seems to be either within this piece of code or the code for my fireball (which I will put next). A few definitions:
pew is a sound effect played when the fireball is shot;
horizMultiplier is the distance from the arm's centre which I would like the fireball to instantiate (also dependant of if the player) is facing left or right); and
orientation is which direction the player is facing (left or right). The fireball is then instantiated facing that same direction.
Fireball Script
public Vector2 speed = new Vector2(); // x and y forces respectively
private Rigidbody2D rb; // shorthand
private float rotation;
void Start()
{
rb = GetComponent<Rigidbody2D>(); // shorthand
rotation = rb.rotation;
if (rotation == 0)
{
rb.AddForce(Vector3.right * speed.x); // propels right
}
if (rotation == 180)
{
rb.AddForce(Vector3.left * speed.x); // propels left
}
}
I believe this code is explanatory enough with comments (if not please comment and I'll address any question). I believe an issue could also be in this piece of code because of the lines: rb.AddForce(Vector3.right * speed.x); and rb.AddForce(Vector3.left * speed.x); as these add directional forces to the object. I don't know is this is objective direction (right or left no matter what direction the object the force is being applied to is facing) or if it's right or left in terms of the object-- say if an object was rotated 90 degrees clockwise and that object had a force applied so that it moves right making the object move downwards.
What I'm expecting to happen is the player's arm will turn so that when a fireball is fired it is fired in the direction the arm is facing. The arms turning mechanics are fine, it's just trying to properly instantiate the fireball. Can anyone help with any of the issues I've laid out?
How I would go about this:
Add an empty transform as child of the arm and move it to where the fireball should spawn. Also make sure the rotation of it is such that its forward vector (the local z-axis) points to where the fireball should go. To see this, you need to set "Local" left of the play button.
Spawn the fireball at the transform's position with its rotation.
Ignore collision between the arm's/player's collider and the fireball's collider with https://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html. If necessary, you can enable the collision between the two colliders again after 1s or so.
Set the fireball rigidbody's velocity to speed * rigidbody.forward.
If you need help with the code, please post it so I can see what's going on.
Edit:
The arm definitely doesn't require a Rigidbody.
You can just use Instantiate(prefab, position, rotation) as shorthand.
Is this for a 2D game?
Also, I'm going to sleep now but I'll gladly try to help tomorrow.
Your Issues
1) You should be masking the fireball's layer not to collide with your player's layer.
You can find more info about this here: https://docs.unity3d.com/Manual/LayerBasedCollision.html
(note: make sure you're on the Physics2D panel, and not the Physics one, as that's for 3D)
2) There is a setting called gravityScale in RigidBody2D. You should set this to 0 if you don't want gravity to be affecting your object. More info: https://docs.unity3d.com/Manual/class-Rigidbody2D.html
Fireball Instantiate
if (Input.GetKeyDown(KeyCode.Space))
{
pew.Play();
var position = hand.transform.position + hand.transform.forward * horizMultiplier;
var rotation = hand.transform.rotation;
var fireball = Instantiate<Fireball>(fireballPrefab, position, rotation);
fireball.StartMoving();
}
Fireball Script
private Rigidbody2D rb; // shorthand
private float rotation;
public float Speed;
public void StartMoving()
{
rb = GetComponent<Rigidbody2D>(); // shorthand
rb.velocity = transform.forward * Speed;
}
void OnTriggerEnter(....) { .... }

Weird - Transform.Translate

I want to move object to right and to left and i have a weird problem when doing it. I am doing Transform.Translate in update method with If(Input..)
This is my code for moving to right
player.transform.Translate(Vector3.right * Time.deltaTime * varLeftRight, Space.World);
(I tried to use ("player") with gameobject attached in inspector and I tried to use rigidbody ("b") but it doesn't help same issue happens))
where the variable varLeftRight is 125.
I am adding force to go forward in oncollision like this:
b.AddForce(Vector3.forward * speed);
And lets say my player is on coordinates:
-0.074 ->x
-1.5166 ->y
4.173041 -z
I put on player rigidbody is kinematic because I want to test why same issue happens when playing. The problem is when I click once it works and moves right
Cordinates with one click:
1.592691
-1.5166
4.173041
But the problem is when i click twice very fast the player position brakes and goes too much to right.
With twice fast clicks to go to right he goes too much and when I get back one field he need to be on this coordinates:
1.592691
-1.5166
4.173041
and he is on this cordinates:
2.101478
-1.5166
4.173041
Idk did I described issue good. I hope you will understand me,
so when I click once to move with trasnform.translate everything works fine
when I click twice quickly he goes too much to right and when I get back one field to see where is he with one click he is not on right place, to go back to left one field is the same method only with adding left parametar like this:
player.transform.Translate(Vector3.left * Time.deltaTime*varLeftRight, Space.World);
I tried removing the Space.World but it doesn't help.
btw: my obstacle collision have all rigidbody is kinematic to true (Tried without rigidbody same issue happens.
In on Collision I am adding force to go forward no other scripts in code.
public class PlayerControl : MonoBehaviour
{
public float bounce;
public float speed;
public float right;
Rigidbody rb;
public GameObject player;
public float varLeftRight;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
rb.AddForce(Vector3.forward * speed);
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Debug.Log("add force");
player.transform.Translate(Vector3.right * Time.deltaTime * varLeftRight, Space.World);
}
if (Input.GetMouseButtonDown(1))
{
player.transform.Translate(Vector3.left * Time.deltaTime*varLeftRight, Space.World);
}
}
private void OnCollisionEnter(Collision collision)
{
rb.AddForce(Vector3.forward * speed);
}
}
I couldn't make sense of why you're adding force on collision, but I have a feeling that's where the issue lies.
I'd comment that out to see if you're still having an issue.
Say that's really the problem, maybe consider only adding force on collision on the proper circumstances (ie. if the player is just colliding with the ground should they get force? or just if colliding with certain elements? etc)

Categories