Rotating gameobject with Joystick - c#

Trying to rotate my gameObject with Joystick, I did previously a script that gameobject was facing mouseInput and I want exactly the same but while using joystick?
public class FaceMouse : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButton(0))
{
Rotation();
}
}
void Rotation()
{
Vector3 mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
Vector2 direction = new Vector2(
mousePosition.x - transform.position.x,
mousePosition.y - transform.position.y);
transform.up = direction;
}
}
I was searching and I found this script, but gameobject doesn't rotate like clock, it rotate my gameobject on other axis, any idea how to make my object to copy JOYTICK movement just like in first script ?
public class PlayerMovements : MonoBehaviour
{
public FixedJoystick joystick;
public float speed = 10f;
public float roatateSpeed = 40f;
public GameObject rb;
private void Start()
{
rb = GetComponent<GameObject>();
}
private void Update()
{
float horizontal = joystick.Horizontal;
float vertical = joystick.Vertical;
Vector3 frameMovement = new Vector3(horizontal, 0f, vertical);
Quaternion rotation = Quaternion.LookRotation(frameMovement);
transform.rotation = rotation;
}
}

Try This
float AxisFactor = 90;
transform.localEulerAngles += new Vector3(vertical, horizontal, 0)*AxisFactor*Time.deltaTime;

Related

Sprite not Appearing in Unity 2D Game

I'm creating a 2D Top Down game for practice and I need a little bit of help. For context, it's a 2D Top Down Shooter game, where you can move and shoot enemies. The enemies have a basic radius system where if the player gets within the radius, it'll approach the player.
Now I'm making a game mechanic where the player can hide in a cardboard box, the player can press 'E' and he'll suddenly become a cardboard box, where if the player is in the cardboard box, the enemy doesn't detect him even if the player's within the radius. Yes, just like in Metal Gear. Now I've created the prefabs and everything and functionality-wise, it works perfectly. If you press 'E' the enemy cannot detect you.
Now the small problem is that the cardboard box didn't appear, so it's just the player disappearing entirely. I do not know what caused this problem.
For context, these are my scripts. Feel free to read them, or not :)
PlayerController:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
public GameObject bulletPrefab;
public GameObject player;
private Rigidbody2D rb2d;
private Vector2 moveDirection;
[SerializeField] private Camera cam;
[SerializeField] private GameObject gunPoint;
public bool isHiding = false;
[SerializeField] private GameObject cardboardBox;
[SerializeField] private GameObject gunSprite;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
cardboardBox.SetActive(false); // Hide the cardboard box when the game starts
gunSprite.SetActive(true); // Show the gun sprite when the game starts
}
// Update is called once per frame
void Update()
{
CheckCursor();
ProcessInputs();
// Make the camera follow the player
cam.transform.position = new Vector3(player.transform.position.x, player.transform.position.y, cam.transform.position.z);
// Check if player pressed the "E" key to toggle the cardboard box
if (Input.GetKeyDown(KeyCode.E))
{
isHiding = !isHiding; // Toggle the isHiding variable
cardboardBox.SetActive(isHiding); // Show/hide the cardboard box accordingly
// If player is hiding, stop player movement
if (isHiding)
{
moveDirection = Vector2.zero;
player.GetComponent<SpriteRenderer>().enabled = false;
cardboardBox.GetComponent<SpriteRenderer>().enabled = true;
gunSprite.SetActive(false); // Hide the gun sprite when the player is hiding
}
else
{
player.GetComponent<SpriteRenderer>().enabled = true;
cardboardBox.GetComponent<SpriteRenderer>().enabled = false;
gunSprite.SetActive(true); // Show the gun sprite when the player is not hiding
}
}
}
private void FixedUpdate()
{
if (!isHiding) // Only allow player to move if they are not hiding in the cardboard box
{
Movement();
}
}
private void CheckCursor()
{
Vector3 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
Vector3 characterPos = transform.position;
if (mousePos.x > characterPos.x)
{
this.transform.rotation = new Quaternion(0, 0, 0, 0);
}
else if (mousePos.x < characterPos.x)
{
this.transform.rotation = new Quaternion(0, 180, 0, 0);
}
}
private void Movement()
{
// TODO : Implementasi movement player
rb2d.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
}
private void ProcessInputs()
{
float moveX = Input.GetAxisRaw("Horizontal");
float moveY = Input.GetAxisRaw("Vertical");
moveDirection = new Vector2(moveX, moveY);
if (Input.GetMouseButtonDown(0))
{
Shoot();
}
}
private void Shoot()
{
Vector3 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
Vector3 gunPointPos = gunPoint.transform.position;
Vector3 direction = (mousePos - gunPointPos).normalized;
GameObject bullet = Instantiate(bulletPrefab, gunPointPos, Quaternion.identity);
bullet.GetComponent<Bullet>().Init(direction);
}
}
EnemyController script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyController : MonoBehaviour
{
public Transform player;
public float moveSpeed = 5f;
public float detectionRadius = 5f;
public int maxHealth = 1;
private int currentHealth;
private Rigidbody2D rb2d;
private Vector2 movement;
private void Start()
{
rb2d = this.GetComponent<Rigidbody2D>();
currentHealth = maxHealth;
}
private void Update()
{
float distanceToPlayer = Vector2.Distance(transform.position, player.position);
if (player != null && distanceToPlayer <= detectionRadius && !player.GetComponent<PlayerController>().isHiding)
{
Vector3 direction = player.position - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
rb2d.rotation = angle;
direction.Normalize();
movement = direction;
}
else
{
movement = Vector2.zero;
}
}
void FixedUpdate()
{
moveCharacter(movement);
}
private void moveCharacter(Vector2 direction)
{
rb2d.MovePosition((Vector2)transform.position + (direction * moveSpeed * Time.deltaTime));
}
public void DestroyEnemy()
{
Destroy(gameObject);
}
}
Bullet script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
// Start is called before the first frame update
[SerializeField] private float speed;
[SerializeField] private Vector3 direction;
public void Init(Vector3 direction)
{
this.direction = direction;
this.transform.SetParent(null);
transform.rotation = Quaternion.Euler(0, 0, Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg);
}
// Update is called once per frame
void Update()
{
this.transform.position += transform.right * speed * Time.deltaTime;
}
// TODO : Implementasi behaviour bullet jika mengenai wall atau enemy
private void OnTriggerEnter2D(Collider2D other)
{
switch(other.gameObject.tag)
{
case "Wall":
Destroy(gameObject);
break;
case "Enemy":
Destroy(gameObject);
other.gameObject.GetComponent<EnemyController>().DestroyEnemy();
break;
}
}
}
I've tried tinkering my scripts, I've tried checking if there are any missing components in the cardboard box game object but to no avail. Although I might be wrong on the Unity part since I'm fairly certain that the script isn't the problem here, again might be wrong.
I appreciate all the help I can get, thank you for reading until here

How I can move player left or right with infinite runner game here. using character controller

public class PlayerMove : MonoBehaviour
{
public float speed;
private float yVelocity;
public CharacterController player;
public float jumpHeight =10.0f;
public float gravity = 1.0f;
//public float gravityScale = 1;
private void Start()
{
player = GetComponent<CharacterController>();
}
void Update()
{
Vector3 direction= new Vector3(0, 0, 1);
Vector3 velocity= direction * speed;
if (player.isGrounded == true)
{
if (Input.GetKeyDown(KeyCode.Space))
{
yVelocity = jumpHeight;
}
}
else
{
yVelocity -= gravity;
}
velocity.y = yVelocity;
player.Move(velocity * Time.deltaTime);
}
}
I tried Rigidbody & much more script but my player doesn't jump if my player jump then my doesn't move left or right sometimes my player stocked in ground.. tell me the right way of script where I can use
For the left/right movements you can try this simple code :
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
public float speed;
private float yVelocity;
public CharacterController player;
public float jumpForce = 10.0f;
public float moveForce = 5.0f;
public float gravity = 1.0f;
private void Start()
{
player = GetComponent<CharacterController>();
}
void Update()
{
Vector3 direction = new Vector3(0, 0, 1);
Vector3 velocity = direction * speed;
// Add left/right movement
if (Input.GetKey(KeyCode.LeftArrow))
{
velocity += Vector3.left * moveForce;
}
else if (Input.GetKey(KeyCode.RightArrow))
{
velocity += Vector3.right * moveForce;
}
if (player.isGrounded)
{
if (Input.GetKeyDown(KeyCode.Space))
{
yVelocity = jumpForce;
}
}
else
{
yVelocity -= gravity;
}
velocity.y = yVelocity;
player.Move(velocity * Time.deltaTime);
}
}
You can also look at this post Moving player in Subway Surf like game using left/right swipe

How to control the curve of a jump mechanic in Unity while using the Rigidbody2D's velocity?

I'm making a platformer controller using the new Input System and trying to control the curve for jumping... I've figured out how to add a damp for the horizontal movement which give the horizonal movement a bit of a slippery feel. But I cannot figure out how to control curve for the Jump. The problem now is I'm using a Player Input Component and Unity Events to control the Move and Jump. And the jump is using rb.velocity.y.
How do I control my Jump curve?
Here is the current curve:
I want to controle the acceleration and deacceleration of the curve:
Here is the curve I'd like to achieve with jumping
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
private const float GroundedRadius = 0.2f;
[SerializeField] private float smoothInputSpeed = .2f;
[SerializeField] private float speed = 8f;
[SerializeField] private float jumpingPower = 12f;
[SerializeField] private float fallPower = 2f;
[SerializeField] private Rigidbody2D rb;
[SerializeField] private Transform groundCheck;
[SerializeField] private LayerMask groundLayer;
private Vector2 _smoothMove = Vector2.zero;
private Vector2 _smoothInputVelocity = Vector2.zero;
private Vector2 _move = Vector2.zero;
private bool _isFacingRight = true;
void Update()
{
_smoothMove = Vector2.SmoothDamp(_smoothMove, _move, ref _smoothInputVelocity, smoothInputSpeed);
rb.velocity = new Vector2(_smoothMove.x * speed, rb.velocity.y);
if (!_isFacingRight && _move.x > 0f || _isFacingRight && _move.x < 0f)
{
Flip();
}
}
public void Move(InputAction.CallbackContext context)
{
_move = context.ReadValue<Vector2>();
}
public void Jump(InputAction.CallbackContext context)
{
if (context.performed && IsGrounded())
{
rb.velocity = new Vector2(rb.velocity.x, jumpingPower);
}
if (context.canceled && rb.velocity.y > 0f)
{
var velocity = rb.velocity;
var gravity = rb.gravityScale;
velocity = new Vector2(velocity.x, (velocity.y * gravity * fallPower)); // fall faster if cancelled
rb.velocity -= velocity;
}
}
private bool IsGrounded()
{
return Physics2D.OverlapCircle(groundCheck.position, GroundedRadius, groundLayer);
}
private void Flip()
{
_isFacingRight = !_isFacingRight;
var transform1 = transform;
Vector3 localScale = transform1.localScale;
localScale.x *= -1f;
transform1.localScale = localScale;
}
}

Moving an object towards a position not working properly

I have written a code to get a random transform from my list pathPoints and move my object based on that transform, but what it is doing is getting multiple transforms and trying to move everywhere at once. I want the object to move at one position then get a new position and move there then repeat.
Here is the code:-
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PathFinder : MonoBehaviour
[SerializeField] List<Transform> pathPoints;
[SerializeField] Transform pathPrefab;
[SerializeField] float moveSpeed = 10f;
[SerializeField] bool isMoving = false;
[SerializeField] bool isH_Attacking = false;
Animator anim;
Transform defaultWayPoint;
Transform currentTargetPoint;
void Awake()
{
anim = GetComponent<Animator>();
defaultWayPoint = pathPrefab.GetChild(0);
}
void Start()
{
currentTargetPoint = pathPoints[Random.Range(0, pathPoints.Count)];
transform.position = defaultWayPoint.position;
}
void MoveToNextWayPoint()
{
if(transform.position != currentTargetPoint.position)
{
float delta = moveSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, currentTargetPoint.position, delta);
anim.SetBool("isMoving", true);
isMoving = true;
}
GetNextWayPoint();
}
Transform GetNextWayPoint()
{
currentTargetPoint = pathPoints[Random.Range(0, pathPoints.Count)];
Debug.Log(currentTargetPoint.position);
return currentTargetPoint;
}
void Update()
{
MoveToNextWayPoint();
}
*The script is attached to the gameObject which I want to move.
*This is a 2d project.
void MoveToNextWayPoint()
{
if(transform.position != currentTargetPoint.position)
{
float delta = moveSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, currentTargetPoint.position, delta);
anim.SetBool("isMoving", true);
isMoving = true;
}
else
{
GetNextWayPoint();
}
}

On Line Renderer will Instantiate GameObject to make a bridge (Unity c#)

I am trying to make a bridge using Line Renderer.
With this script i write on mouse click straight line and when i want somehow use
"startPos" and "endPos" to make that streched gameobject (sprite renderer)
in 2d game.. how to write down Instatiate function? I am lost in this..
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DrawBridge : MonoBehaviour
{
private LineRenderer lineRend;
private Vector2 mousePos;
private Vector2 startMousePos;
[SerializeField]
private SpriteRenderer spriteRender;
private float distance;
[SerializeField]
GameObject spawnBridge;
private void Start()
{
lineRend = GetComponent<LineRenderer>();
lineRend.positionCount = 2;
spriteRender = GetComponent<SpriteRenderer>();
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
startMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
if (Input.GetMouseButton(0))
{
StartDrawn();
}
}
void StartDrawn()
{
mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 startPos = new Vector3(startMousePos.x, startMousePos.y, 0f);
lineRend.SetPosition(0, startPos);
Vector3 endPos = new Vector3(mousePos.x, mousePos.y, 0f);
lineRend.SetPosition(1, endPos);
distance = (mousePos - startMousePos).magnitude;
// Instantiate(spawnBridge, startPos, endPos, transform.rotation.);
}
}

Categories