I am working on a 2D Platform game, and i realized that the player's jumping function doesn't work the same way every time, for example. The jumping height is different if the player jumps while moving/running or if the player jumps without moving.
I have 2 separated functions Move() and Jump(), Move() uses transform.Translate to make the player move, and Jump() uses rigidBody.AddForce() to make the player jump. I've already tried to change the player Move() function to use rigidBodies to make the player move instead of using transform.Translate(). And it didn't worked.
I've also tried make the player jump using transform.Translate, which solved the inconsistent jumping height problem, but the player just teleports up instead of jumping
this is a representation of my code structure, not the actual code, because the actual code is like 600 lines
public class Player
{
float JumpSpeed;
bool isGrounded;
void Update()
{
if (Input.GetKey(KeyCode.A))
Move(Directions.Left);
if (Input.GetKey(KeyCode.D))
Move(Directions.Right);
if (Input.GetKeyDown(KeyCode.Space))
Jump(JumpSpeed);
}
public void Move(Directions dir)
{
Vector2 speed;
//figure out speed and etc...
//makes the player move in the right direction and speed
transform.Translate(speed * Time.deltaTime);
}
public void Jump(float speed)
{
if(isGrounded)
rigidBody.AddForce(new Vector2(0, speed * Time.deltaTime), ForceMode2D.Impulse);
}
}
Not sure if this is specifically your issue, but using translate to move the player and then adding force to jump isn't really the best way to approach the problem.
I would look into using the velocity part of the rigidbody for both the jump and the movement. This would prevent any weirdness that Translating the object could cause.
Related
Hello all, I'm very new to and very confused by Unity.
I'm creating a top-down, gravity-free test game, similar to PacMan (i.e. think of the movement of characters in straight lines).
Currently, I'm trying to move an object in straight lines (without curvature) (see image).
My GameObject has RigidBody2D attached, as well as Linear, Angular and Gravity set to 0.
I'm currently controlling my GameObject by adding force:
private Rigidbody2D _playerRB2D;
public float _speed;
private void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector2 movement = new Vector2(moveHorizontal, moveVertical);
_playerRB2D.AddForce(movement * _speed);
}
The idea is that the game object won't get to slow down, so is constantly in motion (in straight lines). Collision with objects is obviously important too!
Any help or information to look at will help a lot, thank you!
Unity has a built-in physics engine that calculates movement based on velocity (and collisions, etc.) By using Rigidbody2D.AddForce, you are adding to your rigidbody's velocity. This means that if you press the up arrow and then the right arrow, the velocity from pressing the up arrow remains, causing a diagonal velocity and curved path. If you want straight lines, you can use Rigidbody2D.velocity or just use Transform.translate.
_playerRB2D.velocity = movement * _speed;
Edit: You said that collisions were important, so keep the rigidbody
or remove the rigidbody2D component and use
transform.Translate(movement * _speed);
The idea is basically to reset the force being applied on the rigidBody2D on each changed direction.
In fact, you would have to test if the direction input from horizontal is greater than vertical for x axis, and the inverse for y axis , and thus if it is true, change the opposite to 0f.
You would have normally:
Vector2 movement = new Vector2(moveHorizontal < moveVertical ? moveHorizontal: 0f, moveVertical < moveHorizontal ? moveVertical: 0f);
_playerRB2D.velocity = movement * speed;
Edit: By testing the input value, you can move your RigidBody2D with a analogic controller, and thus being straight as you wished !
I have a script that makes the swamp track and follows the player. It workes fine. But when I ad an animation to the enemy (a swamp jumping towards the player) it doesn't move.
I've tried removing the position under animation, but then the swamp does not jump. It just scales. This does though fixe the problem with not following the player. so I think the problem is the animation on the position.
public class EnemyAI : MonoBehaviour
{
public float speed;
private Transform playerPos;
void Update()
{
transform.position = Vector2.MoveTowards(transform.position, playerPos.position, speed * Time.deltaTime);
}
}
Animation is the reason that takes over the position and the script becomes useless. As you have mentioned it jumps (Y-axis) and the position in the animator controller takes over. I would suggest try doing two things:
(a) Add a parent to this swamp gameObject and add animation for jumping to this parent
(b) Add MoveTowards() function to Swamp gameObject.
Through this, the parent gameObject will only perform animation of jumping and the child gameObject will perform MoveTowards() function.
I'm looking for solution to smooth transform position of my object.
To moving to new position I'm using that code
transform.position += Vector3.left * Time.deltaTime * 100f;
The effect of moving is to fast, so I want to make it more smooth. There is any option to change this code for better effect? Like the small bricks in this video when ball destroy big brick
https://youtu.be/mqj7eYna3Ds
You can also use this:
transform.Translate(Vector3.left * Time.deltaTime * 100f);
This should make it a bit smoother. Just remember if you would ad a velocity to the object, Transform.Translate wil not work nice!
if you want more float like movement you can give a Addforce to the attached rigidbody.
rigidbody.AddForce(transform.left * 10, Forcemode.Impulse);
Note: If you use Translate there wil not be any acceleration!
Rigidbody.AddExplosionForce may solve your problem but you cannot put the collision point as the origin. you may have to move your origin of an explosion a little bit below than the collision point. Let me know if it solves the issue.
https://docs.unity3d.com/ScriptReference/Rigidbody.AddExplosionForce.html
Using AddForce or manipulating the velocity variable on the Rigidbody is better if you want smooth movement.
However, if your object doesn't have a rigidbody, then you can just use the functions provided with the Transform class (e.g: Rotate(), Translate(), SetPositionAndRotation())
You can use this block of code to smooth out the movement of the player
public Transform player;
public Vector3 targetPosition;
public float smoothFactor = 2;
void Update()
{
player.transform.position = Vector3.Lerp(player.transform.position, targetPosition, Time.deltaTime * smoothFactor);
}
I want a gameobject spinning around its y-axis. This spinner should have a initial movement direction and when colliding with something, it should change its direction.
I created a little picture to show what I mean, but I want the behaviour for a 3D game.
So I just started with the rotation of the spinner,
public class Spinner : MonoBehaviour
{
[SerializeField]
private float movementSpeed; // speed when moving
[SerializeField]
private float rotationSpeed; // speed when rotating
private Rigidbody rigid;
private Vector3 movementDirection; // the direction the spinner is moving
private void Start()
{
rigid = GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
transform.Rotate(0, rotationSpeed, 0); // rotate the spinner around its y-axis
}
private void OnCollisionEnter(Collision col)
{
// set new direction
}
}
How can I move the spinner, that it moves along a direction and whenever it collides with something, it changes its direction. It should never stop moving or rotating.
I would like to point out a few things:
The Unity Physics Engine will make collisions to absorb part of the force which moves your spinner, so unless you keep adding "artificial" forces to the spinner it will eventually stop.
The "air friction" in your scene will also reduce the force of your
spinner, so it will slow it down. You should add a material to the
spinner which has 0 Dynamic Friction
Based on the comment you left in #reymoss' answer, you may consider
to add the bouncy material to the walls, and not to the spinning
GameObject.
To sum up, the issue here is if you want a GameObject to bounce against a wall using the Physics Engine, the object will eventually stop, because some of the forces will be absorbed in each collision. That means you will need to keep adding external forces every time a collision takes place, to keep it moving endlessly.
Something you can try is,
1- Add a bouncy material to the walls and remove the dynamic friction of your spinner. In the following link you can learn about this:
https://docs.unity3d.com/Manual/class-PhysicMaterial.html
2- Add to the Spinner a Collider, so when it detects a collision with a wall (you can tag the walls as so for example) add an additional force to the spinner in the direction it is already moving, so it will compensate the energy lost during the collision.
void OnTriggerExit(Collider other) {
if(other.tag == "wall") {
rigidbody.AddForce(rigidbody.velocity.normalized * Time.deltaTime * forceAmount);
}
}
The idea is to let the Engine decide the direction of the Spinner after the collision with the wall, and as soon as the GameObject leaves the trigger, you add an additional force in the current direction.
Then you can play with the Bounciness of the wall's material and with the forceAmount, until your spinner moves as you have in mind.
Note: Since you will have 2 materials, one in the walls and another in the spinner, maybe playing with the Friction Combine and Bounce Combine you will be able to avoid the force lost during collisions, so you will not need to add the external force I mention in the second step. However I have never tried this.
Let me know if it works. I can't try myself the solution until I arrive home.
If you give the object an initial velocity, attach a collider, create and assign a Physics Material 2D to the collider (to apply bounciness), and attach Colliders to the walls, you can have it bounce around with minimal code.
private void Start()
{
rigid = GetComponent<Rigidbody>();
rigid.velocity = new Vector3(2f, 3f, 1f) // initialize velocity here
}
I have a Rigidbody attached to my character controller and my enemies. I want the enemies to be able to surround me and have me trapped without me being able to move, so I set the mass property accordingly.
There's just a small problem - if I don't set my mass high enough, the moment the enemies collide with me, my player will go flying into the air. If I don't set my enemies' mass high enough, I will be able to walk right through them. How can I fix this issue? Here is the movement code for the player:
using UnityEngine;
using System.Collections;
public class CharController : MonoBehaviour {
public float speed;
void Start () {
Cursor.lockState = CursorLockMode.Locked;
}
void Update () {
float translation = Input.GetAxis ("Vertical") * speed;
float strafe = Input.GetAxis ("Horizontal") * speed;
translation *= Time.deltaTime;
strafe *= Time.deltaTime;
transform.Translate (strafe, 0, translation);
if (Input.GetKeyDown ("escape")){
Cursor.lockState = CursorLockMode.None;
}
}
}
The problem here is that you're using Transform.Translate() to move your player object. As a result, the player is being moved into clipping with your enemy objects in between physics calculations - so when the next physics calculation comes around, there will be a massive repulsing force to correct this. This is what's sending your player flying.
A better alternative is to use Rigidbody.AddForce() (or one of its variants) to indirectly move your player object. This allows the player object's movement to be taken into account during physics calculations, so it can collide with and be stopped by enemy objects before it starts clipping into them.
If you retrieve and store a reference to the player's Rigidbody in a variable, then you can replace Translate() with something like:
rigidbody.AddRelativeForce(strafe, 0, translation);
Hope this helps! Let me know if you have any questions.
Make sure IsKinematic is checked. UseGravity can be checked or not depend on your situation.
That way, you rigidbody will not be affected by force, collision or joint and is under full control of your script. But maybe they will lose the ability to detect collision as well but I'm not so sure, I haven't tested it yet.
If that was the case, uncheck the IsKinematic and instead, check FreezeRotation and FreezePosition as well. That way, you revoke control of the physics from affecting your position and rotation. You will manually manipulate position & rotation from your script (using CharacterController).
References:
https://docs.unity3d.com/ScriptReference/Rigidbody-isKinematic.html
https://docs.unity3d.com/Manual/class-Rigidbody.html