How to Jump by Button UI using Character Controller in Unity3D - 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.

Related

How to create a button that slides out when the mouse hovers over it? (Unity2D)

I have a button that I want to slide out from Y position 295 to 205 when the mouse hovers/touches the button, than slides back if the mouse no longer touches the button.
This is my code, the script is on the button I want to move, I tried using RaycastHit2Ds to detect mouse position.
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class SlideButton : MonoBehaviour
{
public Button button;
float slideDownY = 205f;
float slideUpY = 295f;
public float slideSpeed = 5f;
public RectTransform rectTransform;
private void Start()
{
button.onClick.AddListener(OnButtonClick);
}
// Update is called once per frame
void Update()
{
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if(hit.collider != null)
{
Debug.Log("success");
rectTransform.anchoredPosition = Vector2.Lerp(rectTransform.anchoredPosition, new Vector2(rectTransform.anchoredPosition.x, slideDownY), slideSpeed * Time.deltaTime);
}
else
{
rectTransform.anchoredPosition = Vector2.Lerp(rectTransform.anchoredPosition, new Vector2(rectTransform.anchoredPosition.x, slideUpY), slideSpeed * Time.deltaTime);
}
}
void OnButtonClick()
{
// add after slider works
}
}
I have also tried OnMouseEnter/OnMouseExit and OnPointerEnter/OnPointerExit but none have worked either. I haven't found anything that has solved this problem, other answers are all in different languages or not specific enough to help.

Unity: 3D top-down rotate item around player

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;
}
}
}

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

Unity2D How do i get the main camera to move up on the Y axis continuously after i left mouse click?

I'm trying to get my main camera to move upwards on the Y axis slowly only after the left mouse button is clicked.
Here is my code so far.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class CameraPanUp : MonoBehaviour
{
public float speed = 5f;
public Transform target;
Vector3 offset;
// Start is called before the first frame update
void Start()
{
offset = transform.position - target.position;
}
// Update is called once per frame
void FixedUpdate()
{
Vector3 targetCamPos = target.position + offset;
transform.position = Vector3.Lerp(transform.position, targetCamPos, speed * Time.deltaTime);
if (Input.GetMouseButtonDown(0))
{
}
}
}
I'm unsure what to put in the if statement above. I tried using transform.Translate before and it just made the Camera move up in small increments every time i left click. Why is that? Any help would be gladly appreciated.
One option is to use Coroutines:
Coroutine moveCoroutine;
IEnumerator StartMovingUp() {
float moveSpeed = 2f;
while(true) {
transform.Translate(0, moveSpeed * Time.deltaTime, 0);
yield return null;
}
}
void Update() {
if (Input.GetMouseButtonDown(0) && moveCoroutine == null) {
moveCoroutine = StartCoroutine(StartMovingUp());
}
}
another is doing it in the Update function with fields for state. Anything more may make the code too complicated.
bool isMovingUp;
float moveSpeed = 2f;
void Update() {
if (Input.GetMouseButtonDown(0)) {
isMovingUp = true;
}
if (isMovingUp) {
transform.Translate(0, moveSpeed * Time.deltaTime, 0);
}
}

How to move yoke in the vertical axis

I am trying to move an airplane yoke in the vertical axis. I am using the mouse pointer to move yoke in vertical axis up and down and clamped the value. When I run the script the yoke is positioned some ever and not moving up and down. The yoke is not moving up and down. How to move yoke up and down as shown in the image using below code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace plane
{
public class IP_AirplaneThrottle_Physical : MonoBehaviour
{
#region Variables
public float maxZOffset = -0.5f;
public float sensitivity = 0.001f;
public float smoothSpeed = 8f;
public bool isHitting = false;
public float wantedDelta;
private Vector3 startPos;
private Vector3 wantedPos;
private Vector2 lastMousePosition;
#endregion
#region Builtin Methods
// Use this for initialization
void Start()
{
//Get the lever starting position
startPos = transform.position;
}
// Update is called once per frame
void Update()
{
HandleRaycast();
HandleInteraction();
}
#endregion
#region Custom Methods
void HandleRaycast()
{
//Build a ray so we can see if we are hitting the lever
Ray curRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
//Do our Raycast into the scene
if(Physics.Raycast(curRay, out hit, 1000f))
{
if(hit.transform.GetInstanceID() == this.transform.GetInstanceID())
{
Debug.Log("Hitting the Lever!");
if(Input.GetMouseButtonDown(0))
{
//We are hitting so get the start mouse position
isHitting = true;
lastMousePosition = Input.mousePosition;
print ("123");
}
}
}
//If we let go of the left mouse button then stop everything
if(isHitting && Input.GetMouseButton(0) == false)
{
isHitting = false;
}
}
void HandleInteraction()
{
if(isHitting)
{
//Calculate the delta for Z offset
wantedDelta = (lastMousePosition.y - Input.mousePosition.y) * Time.deltaTime * sensitivity;
startPos.z += wantedDelta;
//make sure we dont go to far
startPos.z = Mathf.Clamp(startPos.z, maxZOffset, 0f);
wantedPos = startPos;
//Get the New Mouse Position every frame while we are holding
lastMousePosition = Input.mousePosition;
}
else
{
//Clear out the Delta value
wantedDelta = 0f;
}
//Move the lever
transform.position = Vector3.Lerp(transform.position, wantedPos, Time.deltaTime * smoothSpeed);
}
#endregion
}
}