Unity: 3D top-down rotate item around player - unity3d

I'm trying to get an object to always be "in front" of the player, from a top down perspective. Here's screenshots demonstrating what I'm trying to do.
So as you can see, when the blue capsule (player) picks up the green capsule (item), the item correctly hovers in front of the player (indicated by the z-axis blue arrow), but when the player turns in any other direction, the item doesn't follow, and instead stays in exactly the same position relative to the player.
My player controller script looks as follows:
using UnityEngine;
public class PlayerController : MonoBehaviour {
public float movementSpeed = 10;
private Rigidbody body;
private Vector2 movement;
void Start() {
body = GetComponent<Rigidbody>();
}
void Update() {
movement.x = Input.GetAxis("Horizontal");
movement.y = Input.GetAxis("Vertical");
}
void FixedUpdate() {
body.velocity = new Vector3(movement.x * movementSpeed * Time.deltaTime, 0, movement.y * movementSpeed * Time.deltaTime);
// this is what updates the direction of the blue arrow in the direction of player movement
if(movement.x != 0 || movement.y != 0) {
body.rotation = Quaternion.LookRotation(body.velocity);
}
}
}
And here's my pickup script (where the item's position is supposed to be updated):
using UnityEngine;
public class Pickup : MonoBehaviour {
private GameObject item;
public float carryDistance = 1;
void OnCollisionEnter(Collision collision) {
if(collision.gameObject.CompareTag("Item")) {
item = collision.gameObject;
}
}
void Update() {
if(item) {
item.transform.position = transform.position + new Vector3(0, 0, carryDistance);
}
}
}
So to reiterate my question: How can I update the item's position such that it's always hovering next to the player on the side of the blue arrow?

You can achieve this by using players transform.forward
item.transform.position = transform.position + (transform.forward * carryDistance)
+ (Vector3.up * carryHeight);
Alternatively you can just add empty child gameobject to the player, position it in front of the player and use its transform position and rotation to position the picked up object.
public class Pickup : MonoBehaviour {
public Transform pickupPositionTransform;
private GameObject item;
public float carryDistance = 1;
void OnCollisionEnter(Collision collision) {
if(collision.gameObject.CompareTag("Item")) {
item = collision.gameObject;
}
}
void Update() {
if(item) {
item.transform.position = pickupPositionTransform.position;
item.transform.rotation = pickupPositionTransform.rotation;
}
}
}

Related

How to Jump by Button UI using Character Controller in Unity3D

I am calling JUMP function from a UI Button but unable to jump using Character Collider provided by Unity. Can someone please help me where am i going wrong?
PlayerMovement Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class PlayerControllerCC : MonoBehaviour
{
public FixedJoystick moveJoystick;
CharacterController _charController;
private Vector3 v_movement;
private Animator _animator;
public float moveSpeed = 0.1f;
public float gravity = 0.5f;
public float jumpForce = 0.5F;
private float originalstepOffset;
private float InputX;
private float InputZ;
// Start is called before the first frame update
void Start()
{
moveSpeed = 0.1f;
gravity = 0.5f;
jumpForce = 0.5F;
_charController = GetComponent<CharacterController>();
originalstepOffset = _charController.stepOffset;
_animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
InputX = moveJoystick.Horizontal;
InputZ = moveJoystick.Vertical;
isWalking();
}
private void FixedUpdate()
{
playerMovement();
}
void playerMovement()
{
//Check Gravity
if (_charController.isGrounded)
{
_charController.stepOffset = originalstepOffset;
v_movement.y = -0.5f;
}
else
{
_charController.stepOffset = 0;
v_movement.y -= gravity * Time.deltaTime;
}
//player movement
v_movement = new Vector3(InputX * moveSpeed, v_movement.y, InputZ * moveSpeed);
float magnitute = Mathf.Clamp01(v_movement.magnitude);
v_movement.Normalize();
_charController.Move(v_movement * magnitute);
Vector3 lookDir = new Vector3(v_movement.x, 0, v_movement.z);
//Set rotation facing after player movement
if ((lookDir.x != 0) && (lookDir.z != 0))
{
transform.rotation = Quaternion.LookRotation(lookDir);
}
}
void isWalking()
{
if (InputX == 0 && InputZ == 0)
{
_animator.SetBool("isWalking", false);
}
else
{
_animator.SetBool("isWalking", true);
}
}
public void Attack()
{
_animator.SetTrigger("isAttacking");
}
public void Jump()
{
if (_charController.isGrounded)
{
v_movement.y = jumpForce * Time.deltaTime;
}
}
}
When button is clicked in UI it called the JUMP function. I am not using keyboard but FixedJoyStick hence using button to jump.
My Game looks like this and the UI. The up arrow key is the jump button.
The Game button Up Arrow Jump
Calling Jump Function in Button
Your problem lays on the OnClick() function of the button, it is interacting with the script but the script itself is not attached to any character in this case. What you did works when the script works by itself no matter where is attached (e.g. when you call all the objects with a tag).
What you need to do is to link the object which has the script to the OnClick() in the editor, then select from the dropdown menu the script component and then call the function you want.
Like This.
Image link since I'm new
Notice how what is linked are the Game Objects and then the script is selected.

Jump in using Rigidbody or Character controller

i have been recreating my jump code, i have it all done but i can't add force or anything else.
Here's my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class pBeh : MonoBehaviour
{
CharacterController characterController;
public float MovementSpeed = 1;
public float Gravity = 9.8f;
private float velocity = 0;
private Camera mainCam;
public Rigidbody rb;
public float jumpSpeed = 5.2f;
private Vector3 movingDirection = Vector3.zero;
public CharacterController controller;
public float speed;
float turnSmoothVelocity;
public float turnSmoothTime;
public bool canJump = false;
private void Start()
{
characterController = GetComponent<CharacterController>();
mainCam = Camera.main;
}
void Update()
{
// player movement - forward, backward, left, right
float horizontal = Input.GetAxis("Horizontal") * 10;
float vertical = Input.GetAxis("Vertical") * 10;
Vector3 camRightFlat = new Vector3(mainCam.transform.right.x, 0,
mainCam.transform.right.z).normalized;
Vector3 camForwardFlat = new Vector3(mainCam.transform.forward.x, 0,
mainCam.transform.forward.z).normalized;
characterController.Move((camRightFlat * horizontal + camForwardFlat * vertical)
* Time.deltaTime);
// Gravity
if (characterController.isGrounded)
{
velocity = 0;
}
else
{
velocity -= Gravity * Time.deltaTime;
characterController.Move(new Vector3(0, velocity, 0));
}
if (canJump == true && Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("Jumped");/*
transform.Translate(Vector3.up * 5.0f * Time.deltaTime);
rb.AddRelativeForce(Vector3.up * 8.0f);
rb.AddForce(Vector3.up * 8.0f)
i have tried a lot more, but it just doesn't work.
The sphere (Player) does nothing or shakes.
*/
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "enemy")
{
SceneManager.LoadScene("SampleScene");
}
}
void FixedUpdate()
{
if ((controller.collisionFlags & CollisionFlags.Below) != 0)
{
//Debug.Log("ground");
canJump = true;
}
else
{
canJump = false;
}
}
As i said it works just fine i just can't find reason why i cannot jump.
I have all character controller right and rigidbody too. If you could help i would be happy.
Btw i am beginner so i copied movement to be same as camera. Thanks!
From what I know, rigidbody and character controller do not work together (on the same object) so you have to choose one or the other, if you are using rigidbody then a ground check or similiar stuff would not be necessary since rigidbody is using unity physicis system so a lot of the stuff would be already done for you to simulate physics but you should still read thru the document

Trying to create a nice character controller?

I'm kind of new in the 2D environment of Unity.
I'm trying to create a platformer. For now, I have a simple map and my player.
My simple map and my player
My player have one script attached :
public class Player : MonoBehaviour
{
public float speed;
public float jump;
public GameObject raycastPoint; // Positioned at 0.01 pixel below the player
private SpriteRenderer spriteRenderer;
private Rigidbody2D body; // Gravity Scale of the Rigidbody2D = 50
private Animator animator;
private void Start()
{
spriteRenderer = GetComponent<SpriteRenderer>();
body = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
}
private void Update()
{
float horizontal = Input.GetAxisRaw("Horizontal");
if (horizontal == 1 && spriteRenderer.flipX)
{
spriteRenderer.flipX = false;
}
else if (horizontal == -1 && !spriteRenderer.flipX)
{
spriteRenderer.flipX = true;
}
body.velocity = new Vector2(horizontal * speed, body.velocity.y);
animator.SetFloat("Speed", Mathf.Abs(horizontal));
float vertical = Input.GetAxisRaw("Vertical");
if (vertical == 1)
{
RaycastHit2D hit = Physics2D.Raycast(raycastPoint.transform.position, Vector2.down, 0.01f);
if (hit.collider != null)
{
body.AddForce(new Vector2(0f, jump));
}
}
}
}
For now I have achieved the right and left movements.
For the jump, I have a child gameobject just under the player and I'm firing a raycast to the bottom so I can know if my player is grounded or not.
I have two problems.
PROBLEM NUMBER ONE.
Sometimes I feel like my "AddForce" line is executed multiple times my player is jumping really high
Problem number one image
PROBLEM NUMBER TWO.
When I'm jumping to the left or right wall, if I keep pressing the left or right key my player is not falling anymore and stay against the wall.
Problem number two image
I tried to put my code into the FixedUpdate method (I know it's better) but I had the same results.
And I tried to set the Collision Detection on Continuous but I had the same results.
Try this code for your first problem :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(BoxCollider2D))]
[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(Animator))]
public class Player_Controller : MonoBehaviour {
private Rigidbody2D body;
private bool canJump, facingRight;
private Animator anim;
[SerializeField]
private float moveSpeed, jumpForce;
void Start ()
{
SetStartValues();
}
void FixedUpdate ()
{
float horizontal = Input.GetAxis("Horizontal");
animator.SetFloat("Speed", Mathf.Abs(horizontal));
Flip(horizontal);
Move(horizontal);
Jump();
}
private void SetStartValues()
{
body = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
canJump = true;
facingRight = true;
}
private void Jump()
{
if (Input.GetKeyDown(KeyCode.Space) && canJump)
{
body.AddForce(new Vector2(0, jumpForce));
canJump = false;
}
}
private void Move(float x)
{
body.velocity = new Vector2(x * moveSpeed * Time.deltaTime, body.velocity.y);
}
private void Flip(float x)
{
if (x > 0 && !facingRight|| x < 0 && facingRight)
{
facingRight = !facingRight;
transform.localScale = new Vector2(transform.localScale.x * -1, transform.localScale.y) ;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Ground")
{
canJump = true;
}
}
}
And don't forget to put the "Ground" tag on your ground object.

Jittery movement of the camera when rotating AND moving - 2D top down Unity

I am making a 2d top down game where the player can rotate the camera around himself as he moves through the world.
Everything works fine when the player is moving around the world the camera follows him fine. if he standing still then the camera rotation also works very well. However as soon as I start to do both then there is a jittery in the camera that makes all other objects jitter besides the player.
Now in working with this problem I have found out that this could have to do with the fact that I use rigidbody2d.AddRelativeForce (so physics) to move the player and that his movements are checked in FixedUpdate.
https://forum.unity3d.com/threads/camera-jitter-problem.115224/ http://answers.unity3d.com/questions/381317/camera-rotation-jitterness-lookat.html
I have tried moving my camera rotation and the following scripts to LateUpdate, FixedUpdate, Update you name it. Nothing seems to work. I am sure that there is some sort of delay between movement of the camera and the rotation that is causing this. I am wondering if anyone has any feedback?
I have tried disabling Vsync, does not remove it entirely
I have tried interpolating and extrapolating the rigidbody and although there is a difference it does not remove it entirely. Ironically it seemd if I have it set to none, it works best.
Scripts:
To Follow character, script applied to a gameobject that has the camera as a child
public class FollowPlayer : MonoBehaviour {
public Transform lookAt;
public Spawner spawner;
private Transform trans;
public float cameraRot = 3;
private bool smooth = false;
private float smoothSpeed = 30f;
private Vector3 offset = new Vector3(0, 0, -6.5f);
//test
public bool changeUpdate;
private void Start()
{
trans = GetComponent<Transform>();
}
private void FixedUpdate()
{
CameraRotation();
}
private void LateUpdate()
{
following();
}
public void following()
{
Vector3 desiredPosition = lookAt.transform.position + offset;
if (smooth)
{
transform.position = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed);
}
else
{
transform.position = desiredPosition;
}
}
void CameraRotation()
{
if (Input.GetKey("q"))
{
transform.Rotate(0, 0, cameraRot);
}
if (Input.GetKey("e"))
{
transform.Rotate(0, 0, -cameraRot);
}
}
public void SetTarget(string e)
{
lookAt = GameObject.Find(e).GetComponent<Transform>();
}
}
The character Controller, script applied to the Player, is called in FixedUpdate
private void HandleMovement()
{
if (Input.GetKey("w"))
{
rigid.AddRelativeForce(Vector2.up * speed);
}
if (Input.GetKey("s"))
{
rigid.AddRelativeForce(Vector2.down * speed);
}
if (Input.GetKey("a"))
{
if (facingRight)
{
Flip();
}
rigid.AddRelativeForce(Vector2.left * speed);
}
if (Input.GetKey("d"))
{
if (!facingRight)
{
Flip();
}
rigid.AddRelativeForce(new Vector2(1,0) * speed);
}
}
Try to use Coroutines. I modified some of my scripts to be more familiar to Your code, tried it, and I didn't see any jittery. I hope that will help You.
Camera Class:
public class CameraController : MonoBehaviour {
[SerializeField]
Transform CameraRotator, Player;
[SerializeField]
float rotationSpeed = 10f;
float rotation;
bool rotating = true;
void Start()
{
StartCoroutine(RotatingCamera());
}
IEnumerator RotatingCamera()
{
while (rotating)
{
rotation = Input.GetAxis("HorizontalRotation");
CameraRotator.Rotate(Vector3.up * Time.deltaTime * rotation * rotationSpeed);
CameraRotator.position = Player.position;
yield return new WaitForFixedUpdate();
}
}
private void OnDestroy()
{
StopAllCoroutines();
}
}
Player Class:
public class PlayerMovement : MonoBehaviour {
[SerializeField]
float movementSpeed = 500f;
Vector3 movementVector;
Vector3 forward;
Vector3 right;
[SerializeField]
Transform CameraRotator;
Rigidbody playerRigidbody;
float inputHorizontal, inputVertical;
void Awake()
{
playerRigidbody = GetComponent<Rigidbody>();
StartCoroutine(Moving());
}
IEnumerator Moving()
{
while (true)
{
inputHorizontal = Input.GetAxis("Horizontal");
inputVertical = Input.GetAxis("Vertical");
forward = CameraRotator.TransformDirection(Vector3.forward);
forward.y = 0;
forward = forward.normalized;
Vector3 right = new Vector3(forward.z, 0, -forward.x);
movementVector = inputHorizontal * right + inputVertical * forward;
movementVector = movementVector.normalized * movementSpeed * Time.deltaTime;
playerRigidbody.AddForce(movementVector);
yield return new WaitForFixedUpdate();
}
}
}
I fixed this problem finally:
First I made my cameraRotation() and follow() into 1 function and gave it a better clearer name:
public void UpdateCameraPosition()
{
if (Input.GetKey("q"))
{
transform.Rotate(0, 0, cameraRot);
}
else if (Input.GetKey("e"))
{
transform.Rotate(0, 0, -cameraRot);
}
Vector3 desiredPosition = lookAt.transform.position + offset;
transform.position = desiredPosition;
}
I then called that function from the character controller straight after the handling of movement. Both calls (handleMovement & cameraPosition) in fixedUpdate.
void FixedUpdate()
{
HandleMovement();
cameraController.UpdateCameraPosition();
}
and the jittering was gone.
So it seems it was imply because there was a slight delay between the two calls as the previous posts I read had said. But I had failed to be able to properly Set them close enough together.
Hope this helps someone.

Rigidbody is being dragged back to bouncy object

I have an object tagged "Bouncy object" that pushes my player on collision; it works but after collision, my player is like being dragged back to the object tagged "Bouncy object", then does the same thing again like a cycle. The code I used is:
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Bouncy object")
GetComponent<Rigidbody2D>().AddForce(transform.right * 38, ForceMode2D.Impulse);
}
I then set the drag on the player's Rigidbody to: 1.49. How would I stop this from happening? What I want is for the object tagged "Bouncy object" to push my player on collision (trigger) then freeze Rigidbody2D for like 2 seconds, then allows me to control my player.
Here is the code you want. I tested just now.
If Cube collide with Block, it bounce to back 0.1 sec and freeze 1 sec.
The key is '-GetComponent ().velocity'.
Here is the screenshot of editor.
public class PlayerController : MonoBehaviour {
public float force = 10f;
float speed = 5f;
float freezeTime = 1f;
bool isCollide = false;
void FixedUpdate ()
{
float dirX = Input.GetAxis ("Horizontal");
float dirY = Input.GetAxis ("Vertical");
Vector3 movement = new Vector2 (dirX, dirY);
if(isCollide==false)
GetComponent<Rigidbody2D> ().velocity = movement * speed;
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Boundary") {
isCollide = true;
GetComponent<Rigidbody2D> ().AddForce (-GetComponent<Rigidbody2D> ().velocity * force, ForceMode2D.Impulse);
Invoke("StartFreeze", 0.1f);
}
}
void StartFreeze()
{
GetComponent<Rigidbody2D> ().constraints = RigidbodyConstraints2D.FreezeAll;
Invoke("ExitFreeze", freezeTime);
}
void ExitFreeze()
{
GetComponent<Rigidbody2D> ().constraints = RigidbodyConstraints2D.None;
isCollide = false;
}
}