Box Collider snapping to Tile Collider but not other Box Colliders. PHYSICS MATERIAL NOT WORKING - unity3d

https://gyazo.com/4715b11e322ff556113efcba3899bba6
On the right is the box collider, working fine colliding with the player.
On the left is the tilemap collider, where the player snaps into the wall until I let go of arrow key.
Here is movement script:
public float movementSpeed = 10f;
private float jumpThreshold = 0.01f;
public float jumpHeight = 5f;
private Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
Debug.Log(Physics2D.gravity.y);
}
// Update is called once per frame
void FixedUpdate()
{
if (Input.GetButton("Jump"))
{
if (rb.velocity.y > -jumpThreshold && rb.velocity.y < jumpThreshold)
{
rb.AddForce(Vector3.up * jumpHeight, ForceMode2D.Impulse);
}
}
rb.AddForce(new Vector3(0f, -jumpHeight, 0f));
transform.position += new Vector3(Input.GetAxisRaw("Horizontal"), 0f, 0f) * movementSpeed * Time.deltaTime;
}

Related

Is there a way to have an object with rigidbody tilt but not rotate (cube)?

I am working on a project where a player can control a cube and move it around. I love having physics on the cube, but when manuevering, it is very difficult to time a jump when the cube is spinning all over the place. I would like the player to be able to move the cube along the ground, and the cube would gradually tilt towards the direction they are moving it, but not flip entirely. I don't know if it would even work conceptually, but if someone could help me figure out how to alter my code to keep it grounded but still tilt. Thank you.
{
public GameObject Camera;
Collider coll;
private bool isGrounded;
Rigidbody rb;
Vector3 velocity;
public float speed = 12f;
public float gravity = -9.8f;
public float jumpStrength = 1000f;
// Start is called before the first frame update
void Start()
{
Camera = GameObject.Find("Main Camera");
rb = GetComponent<Rigidbody>();
}
void OnCollisionEnter(UnityEngine.Collision collision)
{
if (collision.gameObject.tag == "Floor")
{
isGrounded = true;
Debug.Log("Is Grounded");
}
}
void OnCollisionExit(UnityEngine.Collision collision)
{
if (collision.gameObject.tag == "Floor")
{
isGrounded = false;
Debug.Log("Is Not Grounded");
}
}
// Update is called once per frame
void Update()
{
Camera.transform.position = new Vector3(transform.position.x, transform.position.y + 2.38f, transform.position.z - 3.45f);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float mH = Input.GetAxis("Horizontal");
float mV = Input.GetAxis("Vertical");
rb.velocity = new Vector3(mH * speed, rb.velocity.y, mV * speed);
if(isGrounded && Input.GetButtonDown("Jump"))
{
velocity.y = Mathf.Sqrt(3 * -2 * gravity);
}
velocity.y += gravity * Time.deltaTime;
if(Input.GetButtonDown("Jump") && isGrounded)
{
rb.AddForce(0f, jumpStrength, 0f);
Debug.Log("Jump");
}
}
}

Why is my character falling/leaning over on mouse click in unity?

My character using CharacterController seems to be falling over! Is it the rotation that's the issue? I've been hitting my head against the wall for a few days trying to get this solved. any thoughts?
an small vid of what's happening: https://imgur.com/a/AyPvLtm
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
[RequireComponent(typeof(CharacterController))]
public class Player : MonoBehaviour
{
[SerializeField] private float playerSpeed = 10f;
[SerializeField] private float rotationSpeed = 8f;
public float SpeedChangeRate = 10.0f;
private Camera mainCamera;
private Vector3 targetPosition;
private CharacterController characterController;
private Coroutine coroutine;
private int groundLayer;
private void Awake() {
mainCamera = Camera.main;
characterController = GetComponent<CharacterController>();
groundLayer = LayerMask.NameToLayer("Ground");
}
void Update()
{
if (Mouse.current.leftButton.isPressed) Move();
}
private void Move() {
Ray ray = mainCamera.ScreenPointToRay(Mouse.current.position.ReadValue());
Physics.Raycast(ray: ray, hitInfo: out RaycastHit hit);
if (hit.collider && hit.collider.gameObject.layer.CompareTo(groundLayer) == 0) {
if (coroutine != null) StopCoroutine(coroutine);
coroutine = StartCoroutine(PlayerMoveTowards(hit.point));
targetPosition = hit.point;
}
}
private IEnumerator PlayerMoveTowards(Vector3 target) {
while (Vector3.Distance(transform.position, target) > 0.1f) {
Vector3 destination = Vector3.MoveTowards(transform.position, target, playerSpeed * Time.deltaTime);
Vector3 direction = target - transform.position;
Vector3 movement = direction.normalized * playerSpeed * Time.deltaTime;
characterController.Move(movement);
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction.normalized), rotationSpeed * Time.deltaTime);
yield return null;
}
}
}
The reason is that at close distances, the difference between the main player's Target and Pivot point becomes very small and the height will be effective in determining the direction. Just set the direction Y to 0 to solve the problem.
Vector3 direction = target - transform.position;
direction.y = 0;
Figured this out.
It was my capsule collider. I had it set to the X-Axis, causing the collider to be rotated 90 degrees.
So my character would move and then flip to the side. Updating the collider direct to be on the Y-Axis fixed the problem.

cinemachine makes my camera movement laggy in unity

I'm curently using cinemachine to make a third person camera. My player's movements work and i wanted him to look in the direction he is moving but taking in consideration the rotation of the camera. It works when i don't move the camera while moving the player but when i move the camera the rotations of my player are laggy moreover every movement of my camera seems to be laggy too. Sorry for my english i hope it's clear here is my code :
public class ThirdPersonScript : MonoBehaviour
{
[SerializeField] private float speed;
[SerializeField] private float jumpForce;
[SerializeField] private Transform feet;
[SerializeField] private LayerMask floorMask;
[SerializeField] private Transform cam;
private Vector3 direction;
private Rigidbody rb;
private bool canJump;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
direction = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
direction = Quaternion.AngleAxis(cam.rotation.eulerAngles.y, Vector3.up) * direction;
if (direction.magnitude > 1.0f)
{
direction = direction.normalized;
}
direction *= speed;
canJump = Input.GetKeyDown(KeyCode.Space) ? true : false;
}
void FixedUpdate()
{
if (Physics.CheckSphere(feet.position, 0.1f, floorMask))
{
if (canJump)
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
else
rb.velocity = new Vector3(direction.x, 0, direction.z);
}
else
rb.velocity = new Vector3(direction.x, rb.velocity.y, direction.z);
if (direction != Vector3.zero)
{
Quaternion targetRotation = Quaternion.LookRotation(direction);
targetRotation = Quaternion.RotateTowards(transform.rotation, targetRotation, 1080*Time.fixedDeltaTime);
rb.MoveRotation(targetRotation);
}
}
}
and a screenshot of my cinemachine settings and my hierarchy :
Try change the direction in LateUpdate() but not Update() :
void LateUpdate()
{
direction = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
direction = Quaternion.AngleAxis(cam.rotation.eulerAngles.y, Vector3.up) * direction;
if (direction.magnitude > 1.0f)
{
direction = direction.normalized;
}
direction *= speed;
canJump = Input.GetKeyDown(KeyCode.Space) ? true : false;
}
LateUpdate is called after all Update functions have been called. This is useful to order script execution. For example a follow camera should always be implemented in LateUpdate because it tracks objects that might have moved inside Update.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.LateUpdate.html

How to addforce to mouse location with a player movement script?

I have two codes that both work fine by themselves but they don't work together. One code moves the player up, down, left, right. The other code rotates the sprite and will launch the sprite facing the direction of the mouse. I can not get both of these codes to work at the same time. Please could use some help.
1st Script is Movement
public float moveSpeed;
private Rigidbody2D rb;
private Vector2 moveVelocity;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
Vector2 moveInput = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
moveVelocity = moveInput.normalized * moveSpeed;
}
void FixedUpdate()
{
rb.MovePosition(rb.position + moveVelocity * Time.deltaTime);
}
2nd Script is Launching
// Movement
public float thrust = 10f;
public Rigidbody2D rb;
//Aiming
public Camera cam;
Vector2 mousePos;
void Update()
{
//aiming
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
}
void FixedUpdate()
{
Move();
//aim
Vector2 lookDirection = mousePos - rb.position;
float angle = Mathf.Atan2(lookDirection.y, lookDirection.x) * Mathf.Rad2Deg;
rb.rotation = angle;
}
void Move()
{
if (Input.GetMouseButtonDown(0))
{
rb.AddRelativeForce(Vector2.right * thrust, ForceMode2D.Impulse);
}
}

How do i make my character move in the direction of the camera (Unity)

In Unity I want to make it so that when I hold w, instead of going in a single direction I want it to go forward in the direction of my camera how do I do that? (Sorry I'm new to unity)
EDIT: The movement script is:
using UnityEngine;
using System.Collections;
public class Player_Movement : MonoBehaviour {
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
private Vector3 moveDirection = Vector3.zero;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
As indicated by #lockstock, the direction the camera is facing can be retrieved from its transform. Here is an example below if you want to know how to use it.
public class Player_Movement : MonoBehaviour
{
public float speed = 6.0F;
public float jumpSpeed = 8.0F;
public float gravity = 20.0F;
// Drag & Drop the camera in this field, in the inspector
public Transform cameraTransform ;
private Vector3 moveDirection = Vector3.zero;
void Update() {
CharacterController controller = GetComponent<CharacterController>();
if (controller.isGrounded) {
moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
moveDirection = cameraTransform.TransformDirection(moveDirection);
moveDirection *= speed;
if (Input.GetButton("Jump"))
moveDirection.y = jumpSpeed;
}
moveDirection.y -= gravity * Time.deltaTime;
controller.Move(moveDirection * Time.deltaTime);
}
}
This scripts works without any error. I've tested it in Unity myself.
The forward direction of the camera is obtained by using Camera.main.transform.forward
turn your player so the blue axis is facing the same direction as the blue axis on the camera. then drag and drop the camera onto the player. now when you move the player, the camera will follow, and stay behind the player