Why is the ball glitching on the sidewalls unity - c#

I'm trying to build a simple pong game. But everytime my ball touches the left or right wall, it glitches and gets kind of stuck in the wall on the sides.
this is the code to the ball.
i have the physics material friction set to 0 btw.
public float speed;
Vector2 direction;
Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
direction = Vector2.one.normalized;
}
private void FixedUpdate()
{
rb.velocity = (direction * speed);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Walls"))
{
direction.y = -direction.y;
}
else if (collision.gameObject.CompareTag("Player"))
{
direction.x = -direction.x;
}

Related

Why doesn't my coin disappear when my player collides with it?

I just started coding so i still have so much to learn. Unity doesn't give any error when I play the game but also nothing happenes when the player touches the gold. I want the gold to dissapear when the playes touches it but I don't know why it doesn't work. (collision part is the last part)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
private Rigidbody2D myRigidbody;
private Animator anim;
[SerializeField]
private int speed;
private bool lookright;
void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
lookright = true;
}
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
movements(horizontal);
changedirection(horizontal);
}
private void movements (float horizontal)
{
anim.SetFloat ("Walk", Mathf.Abs(horizontal));
myRigidbody.velocity = new Vector2 (horizontal*speed, myRigidbody.velocity.y);
}
private void changedirection(float horizontal)
{
if (horizontal > 0 && !lookright || horizontal < 0 && lookright)
{
lookright = !lookright;
Vector3 direction = transform.localScale;
direction.x *= -1;
transform.localScale = direction;
}
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "gold")
{
other.gameObject.SetActive(false);
}
} }
This is the Unity inspector of the gold
OnCollisionEnter2D(Collision collision) won't fire when you have its IsTrigger set to true. Change it to OnTriggerEnter2D(Collider2D collider) and it will work.
Take a look at the documentation for colliders.

Unity 2d detect collision

I am building my first 2D project in unity, I am stuck in the PlayerMovement script, it's not colliding with neither the walls nor the objects the player is supposed to move by one block and it should push the objects (like in sokoban), but it's not detecting any of these
the player is a capsule which has a capsule collider 2d component and a rigidbody 2d component and the each wall bloack has box collider 2d and tilemap and tilemap collider 2d and a rigidbody 2d.
I tried using the OnDrawGismos() method to detect the object before moving but it's not working
here's my code
public Tilemap wall;
private Vector3 moveToPosition;
private Vector3 movement;
private bool walking;
private float moveSpeed = 2;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
if (!walking)
{
movement.x = Input.GetAxis("Horizontal");
movement.y = Input.GetAxis("Vertical");
if (movement != Vector3.zero)
{
moveToPosition = transform.position + new Vector3(movement.x, movement.y, 0);
Vector3Int wallMapTile = wall.WorldToCell(moveToPosition - new Vector3(0, 0.5f, 0));
if (wall.GetTile(wallMapTile) == null)
{
StartCoroutine(Move(moveToPosition));
}
}
}
}
IEnumerator Move(Vector3 newPos)
{
walking = true;
while ((newPos - transform.position).sqrMagnitude > Mathf.Epsilon)
{
transform.position = Vector3.MoveTowards(transform.position, newPos, moveSpeed * Time.deltaTime);
yield return null;
}
transform.position = newPos;
walking = false;
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawSphere(moveToPosition- new Vector3(0,0.5f,0), 0.2f);
}```
use rb.velocity to control the player movement instead of transform.position because the player would be teleporting not walking

Why does polygon collider 2d restricts movement of player?

I have a cloud which has a polygon collider 2d attached. Also, I have a player that has a box collider 2d attached. When the player lands on the cloud, at some point during the movement, something is stopping him. He is animating but he does not move.
Below is the image of my colliders:
When I start running the game, he moves left and right. So I figured it is not a code issue. At a point, he is stuck at the above position and he cannot move right but he can move left. I guess the polygon collider is stopping him from free movement. When I go back, he is walking and when the reaches the above position, he cannot move forward.
Is there any workaround for this?
Below is my code:
public class Player : MonoBehaviour
{
public float speed = 7f;
public float maxVelocity = 8f;
private Rigidbody2D rb;
private Animator anim;
void Awake()
{
rb = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void FixedUpdate()
{
MovePlayerUsingKeyboard();
}
public void MovePlayerUsingKeyboard()
{
float forceX = 0f;
float velocity = Mathf.Abs(rb.velocity.x);
Debug.Log("Player Velocity : " + velocity);
float direction = Input.GetAxis("Horizontal");
if (direction < 0)
{
if (maxVelocity > velocity)
{
anim.SetBool("Walk", true);
forceX = -speed;
}
//Changing the direction the player faces
Vector3 temp = transform.localScale;
temp.x = -1.3f;
transform.localScale = temp;
}
else if (direction > 0)
{
if (maxVelocity > velocity)
{
anim.SetBool("Walk", true);
forceX = speed;
}
Vector3 temp = transform.localScale;
temp.x = 1.3f;
transform.localScale = temp;
}
else
{
anim.SetBool("Walk", false);
}
rb.AddForce(new Vector2(forceX, 0));
}
}
I think it is because that the collider of your character is stuck at the bumpy part of the cloud's polygon collider.
A solution is to change the character's collider to semi-capsule collider or capsule collider so that the character can walk smoothly on some rough surfaces.

child transform does not move when moving the parent transform

I have a player controlled plattform. When moving to the outer edge, the platform starts to move. The width of the outer triggers are calculated by code.
So the player can move to any direction, he just needs to stay near the edge to trigger the movement.
The player got a Rigidbody attached, the platform too. Here is an image of the inspector of platform I use
and this is the code attached
[SerializeField]
private float speed; // the movementSpeed
[SerializeField]
private float movementTriggerWidth; // width of the triggers at the outer edges
private Vector3 movementDirection = Vector3.zero;
private Rigidbody platformRigid;
private GameObject player;
private float triggerDistance; // distance from center to a trigger
private void Start()
{
player = Globals.GetPlayerObject(); // search for the player Object in the scene
platformRigid = GetComponent<Rigidbody>();
triggerDistance = transform.localScale.x / 2 - movementTriggerWidth; // set the trigger distance
}
private void OnTriggerEnter(Collider col)
{
col.transform.parent = transform; // set the player as a child of the platform
}
private void OnTriggerExit(Collider col)
{
col.transform.parent = null; // leave the platform
}
private void OnTriggerStay(Collider col)
{
if (col.gameObject == player) // only the player can move the platform
{
Vector3 playerPosition = player.transform.position;
Vector3 platformPosition = transform.position;
if (Vector3.Distance(playerPosition, platformPosition) > triggerDistance) // player is in outer trigger?
{
movementDirection = playerPosition - platformPosition; // calculate the movement direction
platformRigid.MovePosition(transform.position + movementDirection * speed * Time.deltaTime); // move the platform
}
}
}
Now the problem:
When jumping on a platform, the player becomes a child of the platform. But when the platform starts moving the player is not affected by this. He doesn't get moved by the platform.
I hope someone can help me solving this "little" ( ? ) bug.
Update:
Here is a picture of the player inspector
Well I went for some tries and this is a working solution for me.
I removed the rigidbody
and took this code
[SerializeField]
private float speed;
[SerializeField]
private float movementTriggerWidth;
private Vector3 movementDirection;
private bool move = false;
private GameObject player;
private float triggerDistance;
private void Start()
{
player = Globals.GetPlayerObject();
triggerDistance = transform.localScale.x / 2 - movementTriggerWidth;
}
private void OnTriggerEnter(Collider col)
{
col.transform.parent = transform;
}
private void OnTriggerExit(Collider col)
{
col.transform.parent = null;
}
private void OnTriggerStay(Collider col)
{
if (col.gameObject == player)
{
Vector3 playerPosition = player.transform.position;
Vector3 platformPosition = transform.position;
if (Vector3.Distance(playerPosition, platformPosition) > triggerDistance)
{
movementDirection = playerPosition - platformPosition;
move = true;
}
}
}
private void FixedUpdate()
{
if (move)
transform.Translate(movementDirection * speed * Time.deltaTime);
move = false;
}
Now the platform is moved by Translate() in the FixedUpdate(). OnTriggerStay() just checks, if the platform should be moved or not.

Automatically jump script

I'm working on a 2D game (for smartphone) which is automatically jumping, and I want to give a player movement (accelerometer) (a similar principle as doodle jump). How to make automatically jumping of 2D sprite? I tried to create an animation but it will not move using the accelerometer. So I coded script for automatically jump but it's not working. any help? (automatically jump means when player hits ground, jump again)
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
Rigidbody2D coll;
void Start(){
coll = GetComponent<Rigidbody2D>();
}
void Update() {
if (coll.gameObject.tag == "Ground") {
moveDirection = Vector3.zero;
moveDirection.x = 1;
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
}
}
}
So can someone give me script when player hit ground, player will jump? I want to move up and to the right.
Player object should have collider2D and rigidbody2D. Ground object should have collider2D and "Ground" tag. This code must be on player object.
public int power;
void Update()
{
transform.position = new Vector3(transform.position.x + Input.acceleration.x, transform.position.y, transform.position.z);
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.collider.gameObject.tag.Equals("Ground"))
{
rigidbody2D.AddForce(Vector2.up * power);
}
}
I hope it works.

Categories

Resources