Hi,
This is an endless runner script. I am using character controller. My player default “y axis” position is 3 (He will be floating without any support). But after Jumping he will go below the “y axis” position 3 .
I want the player “y axis” position to be in position 3 after jumping.
Someone please help me with this script. How to stop the player “y axis” position at 3 after jumping.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class myplayer : MonoBehaviour
{
private const float LaneDistance = 2f;
private CharacterController controller;
private float jumpforce = 7f;
private float speed = 18f;
private float verticalvelocity = 0f;
public float gravity = 12f;
public int desiredLane = 1;
public int verticalLane = 1;
private Animator anim;
bool jumped;
// Start is called before the first frame update
void Start()
{
controller = GetComponent<CharacterController>();
anim = GetComponent<Animator>();
jumped = false;
}
// Update is called once per frame
void Update()
{
if (MobileInput.Instance.SwipeLeft)
{
MoveLane(false);
anim.SetTrigger("moveleft");
}
if (MobileInput.Instance.SwipeRight)
{
MoveLane(true);
anim.SetTrigger("moveright");
}
Vector3 targetPosition = transform.position.z * Vector3.forward;
if (desiredLane == 0)
{
targetPosition += Vector3.left * LaneDistance;
print("des0");
}
else if (desiredLane == 2)
{
targetPosition += Vector3.right * LaneDistance;
print("des2");
}
if (transform.position.y == 3)
{
verticalvelocity = 0f;
if (MobileInput.Instance.SwipeUp)
{
//jump code
jumped = true;
verticalvelocity = jumpforce;
}
}
else
{
//I tried to stop the player at position 3. But he stops at 2.9 or 2.5 some values below 3
if (transform.position.y > 3 && jumped)
{
verticalvelocity -= (gravity * Time.deltaTime);
}
else
{
verticalvelocity = 0;
}
}
Vector3 movevector = Vector3.zero;
movevector.x = (targetPosition.x - transform.position.x) * speed;
movevector.y = verticalvelocity;
movevector.z = speed;
controller.Move(movevector * Time.deltaTime);
}
private void MoveLane(bool goright)
{
if (!goright)
{
desiredLane--;
if (desiredLane == -1)
{
desiredLane = 0;
}
}
else
{
desiredLane++;
if (desiredLane == 3)
{
desiredLane = 2;
}
}
}
}