I'm working on a 2D Unity project where it's a platformer but you controller the character with gravity. For the game, I need to make it so that when you turn the gravity say, up, it should flip the sprite upside down. This is my code so far in the C# script I have that is attached to the character game object.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GravityController2d : MonoBehaviour
{
enum GravityDirection { Down, Left, Up, Right };
public Animator animator;
public GameObject Game_object;
private Vector3 chestPos = new Vector3(6.69f, 1.45f, 0.0f);
void Start()
{
Physics2D.gravity = new Vector2(0f, -9.8f);
}
void FixedUpdate()
{
if (Input.GetKeyDown(KeyCode.DownArrow))
{
Physics2D.gravity = new Vector2(0f, -9.8f);
//flip
}
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
Physics2D.gravity = new Vector2(-9.8f, 0f);
//flip
}
if (Input.GetKeyDown(KeyCode.UpArrow))
{
Physics2D.gravity = new Vector2(0f, 9.8f);
//flip
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
Physics2D.gravity = new Vector2(9.8f, 0f);
//flip
}
}
}
Edit: The tag I used was Unity2D but it auto corrected it to unity3d so thats my excuse for that.
Also: It needs to also be able to flip 90 degrees in case the player switches the gravity to go to the left/right
Assuming you are referring to a SpriteRenderer you can use SpriteRenderer.flipX and SpriteRenderer.flipY and check in which direction your gravity goes like e.g.
// Link in the Inspector
[SerializeField] SpriteRenderer spriteRenderer;
and then
private void UpdateSpriteFlip()
{
// The conditions according to your needs of course
spriteRenderer.flipX = Physics2D.gravity.x < 0;
spriteRenderer.flipY = Physics2D.gravity.y > 0;
}
Related
I am making a 2D platforming game in unity. For some reason, the player is getting stuck in the wall. I have used a Tilemap for the wall, then used tilemap Collider 2D with composite collider. The same thing works fine with the ground.
When I go left facing the wall, it behaves as expected:
When I release the left arrow button, it also shows the expected result:
But when I click right arrow next, the player gets stuck inside the wall:
and cannot get out:
Here is my player movement code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerScript : MonoBehaviour
{
// Start is called before the first frame update
[SerializeField] private float movement_speed = 2;
[SerializeField] private float jump_power = 5;
[SerializeField] private LayerMask groundLayer;
[SerializeField] private LayerMask wallLayer;
private Rigidbody2D rb_player;
private BoxCollider2D boxCollider;
private Animator anim;
private void Start()
{
}
private void Awake()
{
rb_player = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
boxCollider = GetComponent<BoxCollider2D>();
groundLayer = LayerMask.GetMask("ground");
wallLayer = LayerMask.GetMask("wall");
}
// Update is called once per frame
private void Update()
{
float x = Input.GetAxis("Horizontal");
rb_player.velocity = new Vector2(x * movement_speed, rb_player.velocity.y);
//flip the player
if(x > 0.01f)
{
transform.localScale = new Vector3(1, 1, 1);
}
else if(x < -0.01f)
{
transform.localScale = new Vector3(-1, 1, 1);
}
if(Input.GetKeyDown(KeyCode.Space) && isGrounded())
{
jump();
}
anim.SetBool("run", x != 0);
anim.SetBool("jump", !isGrounded());
print("wall: "+isTouchingWall());
print("ground: "+isGrounded());
}
private void jump()
{
rb_player.velocity = new Vector2(rb_player.velocity.x, jump_power);
anim.SetTrigger("jump_trigger");
}
private void OnCollisionEnter2D(Collision2D collision)
{
// if(collision.gameObject.tag == "ground")
// {
// grounded = true;
// }
}
private bool isGrounded()
{
RaycastHit2D raycastHit = Physics2D.BoxCast(boxCollider.bounds.center, boxCollider.bounds.size, 0, Vector2.down, .2f, groundLayer);
return raycastHit.collider != null;
}
private bool isTouchingWall()
{
RaycastHit2D raycastHit = Physics2D.BoxCast(boxCollider.bounds.center, boxCollider.bounds.size, 0, new Vector2(transform.localScale.x,0), .1f, wallLayer);
return raycastHit.collider != null;
}
}
It would be nice if anyone can help me as I am a complete beginner in game development with unity.
The problem
Your pivot point of your player (where your player script is attached) isn't centered like your collider. Because of this, your box collider is being flipped like a page from a book and it lands inside the wall.
To fix it
Make sure that your player pivot point is the same as the center of your BoxCollider2D. This way, your collider won't "teleport" from right to left and bypass walls.
Other tips
I see some beginner's mistakes in your code, so even if you manage to fix your issue, I highly recommend to follow the next tips:
All physic based code (jump, movement, etc.) should go inside FixedUpdate() method and use Time.deltaTime or Time.fixedDeltaTime to keep the same speed (for movement and jump) among computers.
Use the proper naming conventions, your variables should be camel case, no underscores. Methods (and Classes) should always start with a capital letter in C# (PascalCase).
Hopefully this will help you.
I'm making a 2D game where the player moves left and right while dodging falling objects, I put triggers so it doesn't leave the screen but sometimes when it collides with these triggers it passes this collider. I sent an image of the colliders, the Player inspector and also a collider.
Here my Player code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ball : MonoBehaviour
{
public bool isRight;
public float speed;
public Transform pointR;
public Transform pointL;
Rigidbody2D rb;
private SpriteRenderer sprite;
private float maxSpeed;
[Header("PowerUps")]
public float force;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
sprite = GetComponent<SpriteRenderer>();
maxSpeed = 600f;
}
void Update()
{
if(Input.GetMouseButtonDown(0))
{
isRight = !isRight;
}
}
void FixedUpdate()
{
if(isRight)
{
rb.velocity = new Vector2(speed, 0);
rb.AddForce(rb.velocity,ForceMode2D.Force );
sprite.flipX = true;
if(rb.velocity.x >= maxSpeed)
{
rb.velocity = new Vector2(maxSpeed, 0);
}
}
else
{
rb.velocity = new Vector2(-speed, 0 );
rb.AddForce(rb.velocity, ForceMode2D.Force );
sprite.flipX = false;
}
}
void OnTriggerEnter2D(Collider2D collider)
{
if(collider.gameObject.tag =="ColliderL")
{
isRight = !isRight;
}
if(collider.gameObject.tag == "ColliderR")
{
isRight = !isRight;
}
// For PowerUps
if(collider.gameObject.tag == "SpeedUp")
{
StartCoroutine(Seconds());
}
}
IEnumerator Seconds()
{
rb.AddForce(rb.velocity * force);
yield return new WaitForSeconds(5f);
rb.AddForce(rb.velocity * -force);
}
}
I would ideally need to see your scene setup to further pinpoint your mistakes. But these are a few common mistakes that are made:
Tags are case-sensitive. Also, make sure to assign them.
Your collider on one of the object is not 2D; There is Collider, then there is Collider2D.
Your collider is not marked as trigger.
Though there are a few non-related problems with your setup:
rb.velocity.collider doesn't exist. You are looking for rb.velocity.
Ideally you want to set physics changes (velocity, in your case) to FixedUpdate() instead.
If you do want to get colliders from RigidBody, use GetAttachedColliders.
Assuming you are setting up a border which the player can never pass through, you should use a full collider instead of a trigger. This uses OnCollisionEnter2D.
new Vector2(speed, 0* Time.deltaTime);
0 * Time.deltaTime does nothing, since you are multiplying by 0.
What you are looking for is probably new Vector2(speed * Time.deltaTime, 0);. But you don't need to multiply the speed by deltaTime since you are not moving the ball manually via it's Transform.
rb.velocity = new Vector2(speed, 0); should be your result.
I have a physics enabled sphere in my scene and a character that i can move around using WASD. now what i want is that as soon as player hits the ball it should not be physics enabled anymore and move along with player as like the player is holding it in the hands.
What i have tried so far:
i was able to do it but not at all perfect how i want it to be. i tried OnCollisionEnter to detect the collision, i made the sphere a child of the player, i used isKinematic = true as soon as collision is detected and i used Vector3.MoveTowards for the object to follow the position as the player.
I have attached two reference videos below
Reference Clip(The style i am aiming for):https://www.youtube.com/watch?v=fi-GB0RwLr0
MyVersion(This is what i am able to do):https://www.youtube.com/watch?v=JtV11KHY4pU
overall, if you watch the clips you can see how my version is very rigid, stucky, buggy, not so light weight feeling at all. Cut me a slack as well if i did anything way wrong, i started unity like just in the previous month.
This is my Player script through which i am controlling it all
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Player : MonoBehaviour
{
public float MoveSpeed;
[SerializeField]private Rigidbody playerRig;
[SerializeField] private Rigidbody ballRig;
[SerializeField] private GameObject Ball;
[SerializeField] private GameObject heldObj;
private bool isTouching = false;
private Vector3 offset = new Vector3(0, 1, 3);
private Vector3 force;
public float jump;
private bool isGrounded = true;
private void Start()
{
Ball = GameObject.FindGameObjectWithTag("Ball");
ballRig.GetComponent<Rigidbody>();
playerRig.GetComponent<Rigidbody>();
}
void Update()
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
playerRig.velocity = new Vector3(x*MoveSpeed, playerRig.velocity.y,z*MoveSpeed);
Vector3 vel = playerRig.velocity;
vel.y = 0;
if (vel.x != 0 || vel.z != 0)
{
transform.forward = vel;
}
if(transform.position.y < -10)
{
GameOver();
}
ReleaseTheBall();
if (isTouching == true)
{
ballRig.transform.position = Vector3.MoveTowards(ballRig.transform.position, playerRig.transform.position, 5f);
}
}
void Jump()
{
force = new Vector3(0, jump, 0);
if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true)
{
isGrounded = false;
playerRig.AddForce(force, ForceMode.Impulse);
}
}
private void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.tag == "Ball" && heldObj == null)
{
ballRig.isKinematic = true;
// ballRig.constraints = RigidbodyConstraints.FreezeRotation;
ballRig.transform.parent = playerRig.transform;
isTouching = true;
Debug.Log(" BALL PICKED UP AND MOVING ");
heldObj = Ball;
}
}
public void ReleaseTheBall()
{
if (Input.GetKeyDown(KeyCode.Space) && heldObj != null)
{
isTouching = false;
heldObj = null;
ballRig.transform.parent = null;
//ballRig.constraints = RigidbodyConstraints.None;
ballRig.isKinematic = false;
//Vector3 forceDirection = new Vector3(playerRig.transform.position.x, 0, playerRig.transform.position.z);
Vector3 rotationDirection = new Vector3(playerRig.transform.rotation.x, playerRig.transform.rotation.y, playerRig.transform.rotation.z);
ballRig.AddForce(new Vector3(transform.position.x,0,transform.position.z) * 5, ForceMode.Impulse);
ballRig.AddTorque(rotationDirection * 1);
Debug.Log("BALL RELEASED");
}
}
public void GameOver()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
i know there could be some very inefficient lines of code here, feel free to call out those lines as well.
So, basically what i want is that i want my player to pick up the ball as soon as it hits it and the ball should move exactly like player as if he is holding the ball in his hands and when i hit the spacebar i want the ball to be released into the direction i am looking(this part is also very tricky for me), what i am trying to do is i want to do exactly like in the refrence clip. Thanks a lot in advance.
one more thing, when i stop pressing any key to move(WASD), my player transform keeps changing values up and down and it slightly starts moving. i mean when i dont press any key, it still kinda moves.
First of all, you have indeed quite a lot of lines that aren't useful in here and that could be optimized.
Anyway, I hope this will do what you want it to do:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
[RequireComponent(typeof(Rigidbody))]
public class Player : MonoBehaviour {
[Header("Movement Setup")]
[Tooltip("Translation speed in m/s")]
[SerializeField] float _TranslationSpeed;
[Tooltip("Rotation speed in °/s")]
[SerializeField] float _RotationSpeed;
[Tooltip("Interpolation speed [0;1]")]
[SerializeField] float _InterpolationSpeed;
[Tooltip("Strength for jumps")]
[SerializeField] float _JumpingStrength;
[Tooltip("Strength for shoots")]
[SerializeField] float _ShootingStrength;
[Header("Other Settings")]
[Tooltip("Where the helded item will be placed")]
[SerializeField] Transform _ContactPoint;
[Tooltip("Which layers should be considered as ground")]
[SerializeField] LayerMask _GroundLayer;
// The player's rigid body
Rigidbody _Rigidbody;
// Is the player on the ground
bool _IsGrounded;
// Rigidbody of what's the player is helding. Null if the player isn't holding anything
Rigidbody _HeldedItemRigidbody;
// Getter to _IsGrounded, return true if the player is grounded
public bool IsGrounded { get { return _IsGrounded; } }
private void Start() {
_Rigidbody = GetComponent<Rigidbody>(); // The player's rigidbody could be serialized
}
void FixedUpdate() {
float horizontalInput, verticalInput;
// Getting axis
horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");
// Moving toward the x
Vector3 moveVect = transform.forward * _TranslationSpeed * Time.fixedDeltaTime * verticalInput;
_Rigidbody.MovePosition(_Rigidbody.position + moveVect);
// Rotating the player based on the horizontal input
float rotAngle = horizontalInput * _RotationSpeed * Time.fixedDeltaTime;
Quaternion qRot = Quaternion.AngleAxis(rotAngle, transform.up);
Quaternion qRotUpRight = Quaternion.FromToRotation(transform.up, Vector3.up);
Quaternion qOrientationUpRightTarget = qRotUpRight * _Rigidbody.rotation;
Quaternion qNewUpRightOrientation = Quaternion.Slerp(_Rigidbody.rotation, qOrientationUpRightTarget, Time.fixedDeltaTime * _InterpolationSpeed); // We're using a slerp for a smooth movement
_Rigidbody.MoveRotation(qRot * qNewUpRightOrientation);
// This prevents the player from falling/keep moving if there is no input
if (_IsGrounded) _Rigidbody.velocity = Vector3.zero;
_Rigidbody.angularVelocity = Vector3.zero;
if (transform.position.y < -10) GameOver();
if (Input.GetKey(KeyCode.Mouse0) && _HeldedItemRigidbody != null) ShootTheBall();
if (!_IsGrounded) return; // What's below this won't be executed while jumping
if (Input.GetKey(KeyCode.Space)) Jump();
}
void Jump() {
_IsGrounded = false;
_Rigidbody.AddForce(_JumpingStrength * transform.up, ForceMode.Impulse);
}
private void OnCollisionEnter(Collision collision) {
// Checking if the player encountered a ground object
if ((_GroundLayer & (1 << collision.gameObject.layer)) > 0) _IsGrounded = true;
if (collision.gameObject.tag == "Ball") { // this can be improved as tags are error prone
// Setting the item position to contact point
collision.gameObject.transform.position = _ContactPoint.position;
// Getting the rigidbody
_HeldedItemRigidbody = collision.gameObject.GetComponent<Rigidbody>();
// Setting the parent
_HeldedItemRigidbody.transform.parent = transform;
// Setting the body to be kinematic
_HeldedItemRigidbody.isKinematic = true;
// Stopping any movement or rotation
_HeldedItemRigidbody.velocity = Vector3.zero;
_HeldedItemRigidbody.angularVelocity = Vector3.zero;
}
}
public void ShootTheBall() {
// Reverting what's done in OnCollisionEnter
_HeldedItemRigidbody.transform.parent = null;
_HeldedItemRigidbody.isKinematic = false;
// Adding force for the shoot
_HeldedItemRigidbody.AddForce(transform.forward * _ShootingStrength, ForceMode.Impulse);
// Resetting helding item to null
_HeldedItemRigidbody = null;
}
public void GameOver() {
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
}
You have to add a layer, and set the ground to this new layer.
Set up the variable as you like, don't hesitate to mess up with it a little bit to find what suits you (and don't forget to set up the player's mass (in rigidbody) as well!!)
Exemple of setup for the player script
Last things, you have to add an empty game object to your player which will be where the ball will be placed. I know it's a little bit dirty but place it a bit far from the player (more than the ball's radius) or it will bug. We could do something programatically to fix the ball at a spot and adapt this spot to the ball's radius.
This is an example of player
As you can see, I have the empty "player" gameobject which has the rigidbody, the collider and the player script.
The GFX item which is just the capsule.
If you don't know about this: the player game object is actually on the floor (at the player's feet) so it's better for movements. If you do this, don't forget to adjust the player's capsule collider to fit the GFX.
I also have the contact point.
Forget about the nose stuff, it's just a way to see where the player is facing when you just have a capsule.
If you have any question, feel free to ask.
i am working on a Unity 2d game thats rounded about a player dodging random objects while flying...something like flappybird. the game work normal.
But the problem is when the player when touch the top screen edge and keep adding force the player get stuck a while on the edge. i think i need to disable adding force when the player touch the edge of the screen.
I hope u guys help me.
This the player code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Jetpack: MonoBehaviour
{
public GameManager GameManager;
private Rigidbody2D rb;
private float jumpForce = 40f;
private bool engineIsOn;
[SerializeField] private GameObject fire;
void Start()
{
engineIsOn = false;
fire.SetActive(false);
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.Space))
{
engineIsOn = true;
fire.SetActive(true);
}
else
{
engineIsOn = false;
fire.SetActive(false);
}
transform.position = new Vector3(Mathf.Clamp(transform.position.x, -4.5f, 4.5f),
Mathf.Clamp(transform.position.y, -4.5f, 4.5f), transform.position.z);
}
private void FixedUpdate()
{
switch (engineIsOn)
{
case true:
rb.AddForce(new Vector2(0f, jumpForce),ForceMode2D.Force);
break;
case false:
rb.AddForce(new Vector2(0f, 0f), ForceMode2D.Force);
break;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
GameManager.gameover();
}
}
Whenever dealing with Rigidbody then don't set any values via the Transform component!
This might break the physics.
And then basically you already said it: Don't add more upwards force if you are on the edges.
As a simple trick you could set the Y velocity to 0 when hitting the edges like
private void FixedUpdate()
{
// Very unusual to use a switch for a single bool
if (engineIsOn)
{
rb.AddForce(new Vector2(0f, jumpForce),ForceMode2D.Force);
}
// This does absolutely nothing
// Adding a force of 0,0 doesn't change the velocity at all ...
//else
//{
// rb.AddForce(new Vector2(0f, 0f), ForceMode2D.Force);
//}
// Check if currently hitting an edge
// and if so set the velocity on that axis to 0
// also clamp the position then
var velocity = rb.velocity;
var position = rb.position;
if(Mathf.Abs(rb.position.x) >= 4.5f)
{
velocity.x = 0;
position.x = Mathf.Clamp(position.x, -4.5f, 4.5f);
}
if(Mathf.Abs(rb.position.y) >= 4.5f)
{
velocity.y = 0;
position.y = Mathf.Clamp(position.y, -4.5f, 4.5f);
}
rb.velocity = velocity;
rb.position = position;
}
I have a networked game with a ship that the player flies around. The ship is a prefab with a camera. When the app runs, the player can move the ship around and the camera moves with the prefab as expected. However, when another player joins the game, that new player takes control of the camera. Each player still has control of their ship and they can move independently, but the camera follows the most recently joined player ship.
I'm at a loss becuase the camera is the child of the player prefab, so I don't understand how another player can have control of the camera.
I've tried adding a network identity with local player identity, but not sure what else to try.
I would like the camera to follow the local player ship.
Please let me know if anything else would help diagnose this issue.
There isn't really any relevant code, but this code does set the initial camera to inactive so that the prefab camera becomes the active camera...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
public class move : NetworkBehaviour {
public float moveSpeed = 1f;
public float smoothTimeY;
public float smoothTimeX;
private GameObject joystickcont;
private Camera firstcamera;
public Camera shipcamera;
[SyncVar(hook = "OnSetScale")]
private Vector3 scale;
[Command]
public void CmdSetScale(Vector3 vec)
{
scale = vec;
}
private void OnSetScale(Vector3 vec)
{
transform.localScale = vec;
}
void Start () {
if (!isLocalPlayer)
{
return;
}
firstcamera = GameObject.FindWithTag("firstcamera").GetComponent<Camera>();
firstcamera.gameObject.SetActive(false);
shipcamera.gameObject.SetActive(true);
CmdSetScale(gameObject.transform.localScale);
gameObject.transform.localScale = new Vector3(0.05f, 0.05f, 1);
}
void Update () {
if (!isLocalPlayer)
{
return;
}
CmdSetScale(gameObject.transform.localScale);
Vector3 dir = Vector3.zero;
dir.x = Input.GetAxis("Horizontal");
dir.y = Input.GetAxis("Vertical");
joystick moveJoystick = joystickcont.GetComponent<joystick>();
if (moveJoystick.InputDirection != Vector3.zero)
{
dir.x = moveJoystick.InputDirection.x;
dir.y = moveJoystick.InputDirection.y;
}
var rb = gameObject.GetComponent<Rigidbody2D>();
if (dir == Vector3.zero)
{
}
else
{
float heading = Mathf.Atan2(dir.x, dir.y);
transform.rotation = Quaternion.Inverse(Quaternion.Euler(0f, 0f, heading * Mathf.Rad2Deg));
rb.velocity = new Vector3(dir.x * .2f, dir.y * .2f, 0);
}
}
}