The character freezes near the wall unity3d - unity3d

Please tell me, when I move the character with the joystick, the character will get stuck in a regular wall. What could be the problem?
Below is a video demonstration.
When moving with the buttons, the character does not get stuck.
https://www.youtube.com/watch?v=9SiQzLAq-kU
Thanks in advance)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MovePersonal : MonoBehaviour
{
public float speedMove;
public float jumpPower;
private float gravityForce;
private Vector3 moveVector;
private CharacterController ch_controller;
private Animator ch_animator;
private MobileController mContr;
// Start is called before the first frame update
private void Start()
{
ch_controller = GetComponent<CharacterController>();
ch_animator = GetComponent<Animator>();
mContr = GameObject.FindGameObjectWithTag("joy").GetComponent<MobileController>();
}
// Update is called once per frame
private void Update()
{
CharacterMove();
GamingGravity();
}
private void CharacterMove() {
if (ch_controller.isGrounded) {
moveVector = Vector3.zero;
moveVector.x = mContr.Horizontal() * speedMove;
moveVector.z = mContr.Vertical() * speedMove;
if(Vector3.Angle(Vector3.forward, moveVector)>1f || Vector3.Angle(Vector3.forward, moveVector) == 0) {
Vector3 direct = Vector3.RotateTowards(transform.forward, moveVector, speedMove, 0.0f);
transform.rotation = Quaternion.LookRotation(direct);
}
}
else {
}
moveVector.y = gravityForce;
ch_controller.Move(moveVector * Time.deltaTime);
}
private void GamingGravity() {
if (!ch_controller.isGrounded) gravityForce -=20f * Time.deltaTime;
else gravityForce = -1f;
if(Input.GetKeyDown(KeyCode.Space) && ch_controller.isGrounded) gravityForce = jumpPower;
}
}

Related

My idea is to make the bullet, which is fired by the player, follow the enemy

So as previously said I need the bullet to follow the enemy. I'm making a 2d Game and just can't figure out how. I'll appreciate it if someone could help me. Here are my scripts.
Bullet Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerFire : MonoBehaviour
{
float moveSpeed = 25f;
Rigidbody2D rb;
Monster target;
Vector2 moveDirection;
public float firespeed;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector2.right * firespeed * Time.deltaTime, Space.Self);
}
private void OnCollisionEnter2D(Collision2D collision)
{
Debug.Log(collision.transform.name);
Destroy(gameObject);
}
}
Enemy script
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Monster : MonoBehaviour {
[SerializeField]
GameObject bullet;
float fireRate;
float nextFire;
public Image BosshealthBar;
public float BosshealthAmount = 100;
public GameObject effect;
// Use this for initialization
void Start () {
fireRate = 1f;
nextFire = Time.time;
}
// Update is called once per frame
void Update () {
CheckIfTimeToFire ();
if (BosshealthAmount <= 0)
{
Destroy(gameObject);
}
}
void CheckIfTimeToFire()
{
if (Time.time > nextFire) {
Instantiate (bullet, transform.position, Quaternion.identity);
nextFire = Time.time + fireRate;
}
}
public void TakeDamage(float Damage)
{
BosshealthAmount -= Damage;
BosshealthBar.fillAmount = BosshealthAmount / 100;
}
public void Healing(float healPoints)
{
BosshealthAmount += healPoints;
BosshealthAmount = Mathf.Clamp(BosshealthAmount, 0, 100);
BosshealthBar.fillAmount = BosshealthAmount / 100;
}
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag.Equals("BulletPlayer"))
{
TakeDamage(10);
Instantiate(effect, transform.position, Quaternion.identity);
}
}
}
Something like this may help u
Vector3 direction = Target.position - Bullet.position;
float distance = direction.magnitude;
float TargetSpeed = 5
Vector3 Force = direction.normalized * ForceMagnitude;
Bullet.AddForce(Force);
But you will need to add it in yourself since i can't tell how your code speceficly works

player falling into the terrain when falling on it

https://drive.google.com/file/d/1Uc2sys7ZFd686UkQlYAMEDZekFEHZcAr/view?usp=sharing
as u see in the video when I try to jump from the mountain the player just goes through the terrain as if it's not there but I can still move normal and I noticed that whenever I move fast while being off the ground the problem appears like when I first started this level I was jumping and returning to the ground very slowly and whenever I jump and move fast towards a hell the problem occurs so I increased the gravity so that I can't move while jumping but still if I move fast while in the air the player won't collide with the terrain but when I move normally or fast on the ground non of that happen's can anyone help me?
I searched on the internet and I found nothing related to this.
terrain 1 properties:
https://drive.google.com/file/d/1VwelecESLjfD7UseP6lmQ0Kkg-3pwg67/view?usp=sharing
terrain 2 properties:
https://drive.google.com/file/d/1ZH-cIBXlhBMPbmkgZXkQmjt-QVpe6MLu/view?usp=sharing
player properties:
https://drive.google.com/file/d/1vTp3TSuIDcYm3orWhy5X3kw6wwBmwNcE/view?usp=sharing
here are the codes used for this:
mouse lock:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class mouselock : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
}
player movement:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class playermove2 : MonoBehaviour
{
[Header("movement")]
private float movespeed = 10f;
[SerializeField] float airmultiplier = 0.4f;
[SerializeField] Transform oriantation;
private float horizontalmovement;
private float verticalmovement;
private float rbdrag = 6f;
private Vector3 movedirection;
public float movementmultiplier = 10f;
public bool isgrounded;
private float playerhight = 1.8f;
public float jumpforce = 8;
public Rigidbody rb;
public float grounddrag = 6f;
public float aridrag = 2f;
public int number;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void Update()
{
if (number == 11)
{
SceneManager.LoadScene("finish scene2");
}
if (Input.GetKeyDown(KeyCode.LeftShift))
{
movespeed = 25;
}
if (Input.GetKeyUp(KeyCode.LeftShift))
{
movespeed = 20;
}
if (Input.GetKeyDown(KeyCode.Space) && isgrounded)
{
jump();
}
print(isgrounded);
myinput();
controledrag();
}
private void myinput()
{
horizontalmovement = Input.GetAxisRaw("Horizontal");
verticalmovement = Input.GetAxisRaw("Vertical");
movedirection = oriantation.forward * verticalmovement + oriantation.right * horizontalmovement;
}
private void FixedUpdate()
{
moveplayer();
}
void moveplayer()
{
if (isgrounded)
{
rb.AddForce(movedirection.normalized * movespeed * movementmultiplier, ForceMode.Acceleration);
}
else
{
rb.AddForce(movedirection.normalized * movespeed * movementmultiplier * airmultiplier, ForceMode.Acceleration);
}
}
void controledrag()
{
if (isgrounded)
{
rb.drag = grounddrag;
}
else
{
rb.drag = aridrag;
}
}
void jump()
{
rb.AddForce(transform.up * jumpforce, ForceMode.Impulse);
}
}
collisions:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class collisions2 : MonoBehaviour
{
public playermove2 player;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter(Collision other)
{
if (other.gameObject.layer == 6)
{
player.isgrounded = true;
}
}
private void OnCollisionExit(Collision other)
{
if (other.gameObject.layer == 6)
{
player.isgrounded = false;
}
}
}
camera movement:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveCamera : MonoBehaviour
{
[SerializeField] Transform cameraposition;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
transform.position = cameraposition.position;
}
}
player look:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerlook : MonoBehaviour
{
[SerializeField] private float sensX;
[SerializeField] private float sensY;
[SerializeField] Transform cam;
[SerializeField] Transform oriantation;
private float mouseX;
private float mouseY;
private float multiplier = 0.01f;
private float xRotation;
private float yRotation;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update()
{
mouseX = Input.GetAxisRaw("Mouse X");
mouseY = Input.GetAxisRaw("Mouse Y");
yRotation += mouseX * sensX * multiplier;
xRotation -= mouseY * sensY * multiplier;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
cam.transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);
oriantation.transform.rotation = Quaternion.Euler( 0, yRotation, 0);
}
}
triggers:
using UnityEngine;
using UnityEngine.SceneManagement;
public class triggers2 : MonoBehaviour
{
public playermove2 playerMove;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.layer == 8)
{
Destroy(other.gameObject);
playerMove.number++;
}
}
}
score and high score:
using UnityEngine;
using UnityEngine.UI;
public class scoreandhighscore2 : MonoBehaviour
{
public Text highscoretext;
public Text scoretext;
public playermove2 playermove;
// Start is called before the first frame update
void Start()
{
highscoretext.text = "high score: " + PlayerPrefs.GetInt("highscore");
}
// Update is called once per frame
void Update()
{
scoretext.text = "score: " + playermove.number.ToString();
}
private void FixedUpdate()
{
if ( playermove.number > PlayerPrefs.GetInt("highscore"))
{
PlayerPrefs.SetInt("highscore", playermove.number);
}
}
}
sooooo I solved the problem the solution is just converting the collision detection to continuous and just like that the player won't break through the terrain I hope this is helpful for other people
here's a pic of what I did:
https://drive.google.com/file/d/1ati8xQFQxwqAg8eJnmZzrs8D05HGuJLs/view?usp=sharing

Problem with my object that does not stop moving

I made a script for moving an object to the position indicated by the mouse click. If I don't choose to click to another location to move towards, I would like to stop my object if it reaches the previously mentioned position. However, the object doesn't stop when reaching the position and it continues moving.
Here is the code I wrote. I would be grateful if somebody knows how to fix this issue.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
private Vector3 targetPos;
private Rigidbody2D rb;
private bool isMoving;
private Vector2 direction;
public float changeDirCooldown;
private float changeCool;
private bool canChangeDir;
void Start()
{
rb = GetComponent<Rigidbody2D>();
changeCool=changeDirCooldown;
canChangeDir =true;
}
void Update()
{
if (Input.GetMouseButton(0) && canChangeDir)
{
changeDirCooldown = changeCool;
SetTargetPosition();
}
if (changeDirCooldown<=0)
{
canChangeDir = true;
}
else
{
changeDirCooldown -= Time.deltaTime;
}
}
private void FixedUpdate()
{
if (isMoving)
{
Move();
}
if (this.transform.position == this.targetPos)
{
isMoving = false;
rb.velocity = Vector2.zero;
}
}
private void SetTargetPosition()
{
targetPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
targetPos.z = transform.position.z;
direction = targetPos - this.transform.position;
direction = direction.normalized;
isMoving = true;
}
private void Move()
{
rb.velocity = direction * moveSpeed;
canChangeDir = false;
}
}
It's probabily a problem with float number tolerance. This line
this.transform.position == this.targetPos
will almost never result to true, so instead you should do something like this:
Mathf.Abs(this.transform.position.x - this.targetPos.x) < float.Epsilon &&
Mathf.Abs(this.transform.position.y - this.targetPos.y) < float.Epsilon

VirtualJoystick issues with unity5

I have two problems with implementing two Virtual Joysticks in Unity 5: one for player movement (grey color) and the second for camera (orange color) please see the following screenshot:
My problems:
For the Virtual Joystick responsible for player movement, the player object does not rotate in the same direction the Joystick is pressed , it's moving in all directions but not facing the same direction that the Joystick is pressed.
The camera can see through the terrain/ground. How do I prevent that?
The script I'm using from Virtual Joystick :
using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.EventSystems;
public class VirtualJoystick : MonoBehaviour,IDragHandler,IPointerUpHandler,IPointerDownHandler {
private Image bgImg;
private Image joystickImg;
public Vector3 InputDirection{ set; get;}
// Use this for initialization
void Start () {
bgImg = GetComponent<Image> ();
joystickImg = transform.GetChild (0).GetComponent<Image> ();
InputDirection = Vector3.zero;
}
// Update is called once per frame
//void Update () {
//}
public virtual void OnDrag(PointerEventData ped)
{
Vector2 pos = Vector2.zero;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle
(bgImg.rectTransform,
ped.position,
ped.pressEventCamera,
out pos)) {
pos.x=(pos.x/bgImg.rectTransform.sizeDelta.x);
pos.y=(pos.y/bgImg.rectTransform.sizeDelta.y);
float x=(bgImg.rectTransform.pivot.x==1) ? pos.x*2+1 : pos.x*2-1;
float y=(bgImg.rectTransform.pivot.y==1) ? pos.y*2+1 : pos.y*2-1;
InputDirection=new Vector3(x,0,y);
InputDirection=(InputDirection.magnitude>1) ? InputDirection.normalized : InputDirection;
joystickImg.rectTransform.anchoredPosition=
new Vector3(InputDirection.x*(bgImg.rectTransform.sizeDelta.x/3),InputDirection.z*(bgImg.rectTransform.sizeDelta.y/3));
Debug.Log(InputDirection);
}
}
public virtual void OnPointerDown(PointerEventData ped)
{
OnDrag (ped);
}
public virtual void OnPointerUp(PointerEventData ped)
{
//Here is the problem it just goes to zero so fast so my character also moves so fast...how can i make it so motth
InputDirection =Vector3.zero;
joystickImg.rectTransform.anchoredPosition =Vector3.zero;
}
}
The script to move the player:
using UnityEngine; using System.Collections;
public class Motor : MonoBehaviour {
public float moveSpeed = 5.0f;
public float drag = 0.5f;
public float terminalRotationSpeed = 25.0f;
private Rigidbody controller;
private Transform camtransform;
public VirtualJoystick movejoystick;
private void Start()
{
controller =GetComponent<Rigidbody>();
controller.maxAngularVelocity = terminalRotationSpeed;
controller.drag = drag;
camtransform = Camera.main.transform;
}
private void Update ()
{
Vector3 dir = Vector3.zero;
dir.x = Input.GetAxis ("Horizontal");
dir.z = Input.GetAxis ("Vertical");
if (dir.magnitude > 1)
dir.Normalize ();
if (movejoystick.InputDirection != Vector3.zero) {
dir = movejoystick.InputDirection;
}
Vector3 rotatedDir = camtransform.TransformDirection (dir);
rotatedDir = new Vector3 (rotatedDir.x, 0, rotatedDir.z);
rotatedDir = rotatedDir.normalized * dir.magnitude;
controller.AddForce (dir * moveSpeed);
Quaternion eulerRot = Quaternion.Euler(0.0f, 0.0f, rotatedDir.x);
transform.rotation = Quaternion.Slerp(transform.rotation, eulerRot, Time.deltaTime * 10);
}
}
The script I'm using for the camera:
using UnityEngine;
using System.Collections;
public class FreeCamera :
MonoBehaviour {
public Transform lookAt;
public VirtualJoystick camerajs;
private float distance = 200.0f;
private float currentx = 0.0f;
private float currenty = 0.0f;
private float sensitivityx = 1.0f;
private float sensitivityy = 1.0f;
private void Update()
{
currentx += camerajs.InputDirection.x * sensitivityx;
currenty += camerajs.InputDirection.z * sensitivityy;
}
private void LateUpdate()
{
Vector3 dir = new Vector3(0, 0, -distance);
Quaternion rotation = Quaternion.Euler(currenty, currentx, 0);
transform.position = lookAt.position + rotation * dir;
transform.LookAt(lookAt);
}
}
more screenshots :
For question 1:
The code below first turns according to joystick-x direction and then move forward/backward according to joystick-y. In Motor.Update:
private void Update ()
{
Vector3 dir = Vector3.zero;
dir.x = Input.GetAxis ("Horizontal");
dir.z = Input.GetAxis ("Vertical");
if (dir.magnitude > 1)
dir.Normalize ();
if (movejoystick.InputDirection != Vector3.zero) {
dir = movejoystick.InputDirection;
}
Vector3 rotatedDir = transform.TransformDirection (dir); // world direction of joystick direction
Vector3 newDir = Vector3.RotateTowards(transform.forward, rotatedDir, Time.deltaTime * 10f, 0.0F); // turn towards joystick direction
transform.rotation = Quaternion.LookRotation(newDir); // set the new direction
controller.AddForce (transform.forward * moveSpeed * dir.z); // scale force by joystick up/down
}

Unity3D Character Controller set speed through script?

How would I be able to set the speed for going forward and back in the Void FixedUpdate? Or is there a better way for doing this? I need to use the character controller though.
using UnityEngine;
using System.Collections;
public class CharacterControllerz : MonoBehaviour {
public float speed;
private CharacterController playerController;
void Start()
{
playerController = GetComponent<CharacterController>();
}
void Update()
{
}
void FixedUpdate()
{
if (Input.GetKey("right"))
{
playerController.Move (Vector3.forward);
Debug.Log ("RIGHT");
}
if (Input.GetKey("left"))
{
playerController.Move (Vector3.back);
Debug.Log ("LEFT");
}
playerController.Move (Vector3.left);
}
}
public float speed = 5f;
public float jumpStrenght = 8f;
public float gravity = 20f;
private Vector3 moveDirections = new Vector3();
private Vector3 inputs = new Vector3();
void FixedUpdate()
{
CharacterController cc = GetComponent<CharacterController>();
if (cc.isGrounded)
{
if (Input.GetKey("right"))
inputs.z = 1;
if (Input.GetKey("left"))
inputs.z = -1;
if (Input.GetKey("up"))
inputs.y = jumpStrenght;
moveDirections = transform.TransformDirection(inputs.x, 0, inputs.z) * speed;
}
moveDirections.y = inputs.y - gravity;
cc.Move(moveDirections * Time.deltaTime);
}
I think that's what you want but you may have to switch the axis.
Edit: Why is TransformDirection used? Because we want to move the object in a direction which shouldn't be relativ to the object's rotation.