In a simple 2d project in which my player can move to the right and left on x and can also jump to the right and left in height with two other buttons. The problem is, that the player is not supposed to move freely. By pressing one of the buttons the player should only go to the next specific point, so that the player always stops at six different positions on x (while on y he is free and as high as the platform he is currently standing on). To be able to jump realistically, the player must have gravity and a collider to be able to land on the platforms (and move single platforms horizontal).
Thanks to the tutorial which #TEEBQNE linked in the comments I could finally realise this with Unitys Rigidbody2D and the following script. The problem is that the gravity is now behaving strangely. The player only moves down very slowly and in the process pushes Gameobjects underneath it through others. The player has a Dynamic Rigidbody2D with a gravity scale of 2 and a capsule collider 2d. Is that a problem with the script or with the components in the players inspector?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movePlayer : MonoBehaviour
{
public GameObject posChecker1;
public GameObject posChecker2;
public GameObject posChecker3;
public GameObject posChecker4;
public GameObject posChecker5;
public GameObject posChecker6;
public bool go; //Player is allowed to move
public bool grounded; //Player is allowed to jump
public string moveDirection;
public float horizVel = 0; //Movement along x
public float verticVel = 0; //Jump
public int laneNum = 3; //Player starts on lane 3!!
public bool rightButtonMove = false;//
public bool leftButtonMove = false;//
public bool rightButtonJump = false;//
public bool leftButtonJump = false;//
//Animation
private SpriteRenderer spriteRenderer;
private Animator animator;
private void Awake()
{
spriteRenderer = GetComponent<SpriteRenderer>();
animator = GetComponent<Animator>();
}
// Start is called before the first frame update
void Start()
{
posChecker1.SetActive(true);//GameObject.Find("PositionChecker1").SetActive(true);
posChecker2.SetActive(true);
posChecker3.SetActive(true); //Player start on lane 3!!
posChecker4.SetActive(true);
posChecker5.SetActive(true);
posChecker6.SetActive(true);
laneNum = 3;
go = true;
}
// Update is called once per frame
void Update()
{
//Raycast
int playerMask = LayerMask.GetMask("PositionChecker");// !!!
Debug.DrawRay(transform.position, transform.TransformDirection(Vector2.up) * 50f, Color.green);
RaycastHit2D hitCheck = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.up), 50f, playerMask);
//Only the checker objects in the rows next to the player are active
if (laneNum == 1)
{
posChecker1.SetActive(false);
posChecker2.SetActive(true);
}
else if (laneNum == 2)
{
posChecker1.SetActive(true);
posChecker2.SetActive(false);
posChecker3.SetActive(true);
}
else if (laneNum == 3)
{
posChecker2.SetActive(true);
posChecker3.SetActive(false);
posChecker4.SetActive(true);
}
else if (laneNum == 4)
{
posChecker3.SetActive(true);
posChecker4.SetActive(false);
posChecker5.SetActive(true);
}
else if (laneNum == 5)
{
posChecker4.SetActive(true);
posChecker5.SetActive(false);
posChecker6.SetActive(true);
}
else if (laneNum == 6)
{
posChecker5.SetActive(true);
posChecker6.SetActive(false);
}
//Movement
GetComponent<Rigidbody2D>().velocity = new Vector3(horizVel, verticVel, 0);
//Raycast
if (hitCheck)
{
if (moveDirection == "l" && horizVel != 0)
{
laneNum -= 1;
}
if (moveDirection == "r" && horizVel != 0)
{
laneNum += 1;
}
go = true;
horizVel = 0;
verticVel = 0;
grounded = true;
}
if (horizVel == 0)
moveDirection = "";
//Animation
bool flipSprite = (spriteRenderer.flipX ? (horizVel > 0.01f) : (horizVel < 0.01f));
if (flipSprite)
{
spriteRenderer.flipX = !spriteRenderer.flipX;
}
animator.SetBool("grounded", grounded); // -->Jump
animator.SetFloat("velocityX", Mathf.Abs(horizVel));
}
//Button Input
public void RightButton() //
{
if (laneNum < 6 && go)
{
moveDirection = "r";
go = false;
horizVel = 4;
}
}
public void LeftButton()//
{
if (laneNum > 1 && go)
{
moveDirection = "l";
go = false;
horizVel = -4;
}
}
public void RightJump()//
{
if (laneNum < 6 && grounded && go)
{
moveDirection = "r";
horizVel = 4;
verticVel = 7;
go = false;
grounded = false;
}
}
public void LeftJump()//
{
if (laneNum > 1 && grounded && go)
{
moveDirection = "l";
horizVel = -4;
verticVel = 7;
go = false;
grounded = false;
}
}
}
Glad I was able to help in some way and that you figured out your issue!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movePlayer : MonoBehaviour
{
//Player Position x
public GameObject posChecker1;
public GameObject posChecker2;
public GameObject posChecker3;
public GameObject posChecker4;
public GameObject posChecker5;
public GameObject posChecker6;
public int laneNum = 3; //Player starts on lane 3!!
//Player Position y
public float yPos1;
public float yPos2;
public Transform player;
//Movement Variables
public bool go; //Player is allowed to move
public bool grounded; //Player is allowed to jump
public string moveDirection;
public float horizVel = 0; //Movement along x
public float verticVel = 0; //Jump
//Animation
private SpriteRenderer spriteRenderer;
private Animator animator;
private void Awake()
{
spriteRenderer = GetComponent<SpriteRenderer>();
animator = GetComponent<Animator>();
}
// Start is called before the first frame update
void Start()
{
posChecker1.SetActive(true);//GameObject.Find("PositionChecker1").SetActive(true);
posChecker2.SetActive(true);
posChecker3.SetActive(true); //Player start on lane 3!!
posChecker4.SetActive(true);
posChecker5.SetActive(true);
posChecker6.SetActive(true);
laneNum = 3;
go = true;
}
// Update is called once per frame
void Update()
{
//Raycast
int playerMask = LayerMask.GetMask("PositionChecker");// !!!
Debug.DrawRay(transform.position, transform.TransformDirection(Vector2.up) * 50f, Color.green);
RaycastHit2D hitCheck = Physics2D.Raycast(transform.position, transform.TransformDirection(Vector2.up), 50f, playerMask);
//Only the checker objects in the rows next to the player are active
if (laneNum == 1)
{
posChecker1.SetActive(false);
posChecker2.SetActive(true);
}
else if (laneNum == 2)
{
posChecker1.SetActive(true);
posChecker2.SetActive(false);
posChecker3.SetActive(true);
}
else if (laneNum == 3)
{
posChecker2.SetActive(true);
posChecker3.SetActive(false);
posChecker4.SetActive(true);
}
else if (laneNum == 4)
{
posChecker3.SetActive(true);
posChecker4.SetActive(false);
posChecker5.SetActive(true);
}
else if (laneNum == 5)
{
posChecker4.SetActive(true);
posChecker5.SetActive(false);
posChecker6.SetActive(true);
}
else if (laneNum == 6)
{
posChecker5.SetActive(true);
posChecker6.SetActive(false);
}
//Movement
if (grounded)
{
verticVel = GetComponent<Rigidbody2D>().velocity.y;
}
GetComponent<Rigidbody2D>().velocity = new Vector3(horizVel, /*GetComponent<Rigidbody2D>().velocity.y*/verticVel, 0);
//Jump
yPos2 = player.transform.position.y;
if ((yPos2 - 2) >= yPos1 && !grounded)
{
if (moveDirection == "l")
horizVel = -4;
if (moveDirection == "r")
horizVel = 4;
verticVel = verticVel * 0.95f;
}
//Raycast
if (hitCheck)
{
if (moveDirection == "l" && horizVel != 0)
{
laneNum -= 1;
}
if (moveDirection == "r" && horizVel != 0)
{
laneNum += 1;
}
go = true;
horizVel = 0;
verticVel = 0;
grounded = true;
}
if (horizVel == 0 && grounded)
moveDirection = "";
//Animation
bool flipSprite = (spriteRenderer.flipX ? (horizVel > 0.01f) : (horizVel < 0.01f));
if (flipSprite)
{
spriteRenderer.flipX = !spriteRenderer.flipX;
}
animator.SetBool("grounded", grounded); // -->Jump
animator.SetFloat("velocityX", Mathf.Abs(horizVel));
}
//Button Input
public void RightButton() //
{
if (laneNum < 6 && go)
{
moveDirection = "r";
go = false;
horizVel = 4;
}
}
public void LeftButton()//
{
if (laneNum > 1 && go)
{
moveDirection = "l";
go = false;
horizVel = -4;
}
}
public void RightJump()//
{
if (laneNum < 6 && grounded && go)
{
moveDirection = "r";
verticVel = 5;
go = false;
grounded = false;
//
yPos1 = player.transform.position.y;
Debug.Log(yPos1);
//
}
}
public void LeftJump()//
{
if (laneNum > 1 && grounded && go)
{
moveDirection = "l";
verticVel = 5;
go = false;
grounded = false;
//
yPos1 = player.transform.position.y;
Debug.Log(yPos1);
//
}
}
}
I created a function in Unity that is supposed to allow the character to climb. It creates two problems, first of all it somehow interacts with the general movement function. When the character starts running their animation won't stop even when the player isn't moving them. Second of all the character can climb up and down the ladder but won't get off them, even though technically the logic is constructed in such a way that they should just go back to their normal state.
I have tried turning off the climb function in the Update() function so I know the running problem is caused by it, because it works fine without it.
private void Climb()
{
RaycastHit2D ladder = Physics2D.Raycast(transform.position, Vector2.up, 5, whatIsLadder);
float hDirection = Input.GetAxisRaw("Horizontal");
float vDirection = Input.GetAxisRaw("Vertical");
if (ladder.collider != null)
{
if (vDirection > 0.1f)
{
isClimbing = true;
}
}
else
{
if (hDirection > 0.1f)
{
isClimbing = false;
}
}
if (isClimbing == true && ladder.collider != null)
{
rb.gravityScale = 0;
rb.velocity = new Vector2(rb.velocity.x, climbSpeed * vDirection);
if (Mathf.Abs(vDirection) > 0.1f)
{
anim.speed = 1f;
}
else
{
anim.speed = 0f;
}
}
else
{
rb.gravityScale = naturalGravity;
}
}
I'll also give a link to the whole PlayerController script since that might help some people:
https://github.com/Pacal2/Platformer/blob/master/Assets/Scripts/PlayerController.cs
Try resetting the velocity on the rigidbody when he stops climbing, near the end of the function:
//....
{
rb.gravityScale = naturalGravity;
}
into:
{
rb.gravityScale = naturalGravity;
rb.velocity = new Vector2(0.0f, 0.0f);
}
this code also looks suspect
if (ladder.collider != null)
{
if (vDirection > 0.1f)
{
isClimbing = true;
}
}
else
{
if (hDirection > 0.1f)
{
isClimbing = false;
}
}
change to:
if (ladder.collider != null)
{
if (vDirection > 0.1f || vDirection < -0.1f) //if allowed to climb down
{
isClimbing = true;
}
if (hDirection > 0.1f || hDirection < -0.1f) //moving left
{
isClimbing = false;
}
}
for animation speed try:
anim.speed = rb.velocity.x;
I lost a lot of time trying to find what is the problem in code but I can not find the solution why my code is not triggered.
In my previous game when I implemented this code it worked perfectly, now when i implement into new game this same code for touch movement it doesn't work.
I tried to debug the code and put Debug.Log into Update method and when i swipe over screen it doesn't even get trigger.
This is the code:
int left = 0;
int right = 0;
int maxLeftCycles = 5;
int maxRightCycles = 5;
void Start()
{
//touch
left = maxLeftCycles;
right = maxRightCycles;
}
private void Update()
{
timer += Time.deltaTime;
if (Input.GetKeyUp(KeyCode.RightArrow) ||
Swipe.swipe == Swipe.SwipeDirection.right)
{
Swipe.ResetSwipe();
right = 0;
}
if (Input.GetKeyUp(KeyCode.LeftArrow) ||
Swipe.swipe == Swipe.SwipeDirection.left)
{
Swipe.ResetSwipe();
left = 0;
}
}
void FixedUpdate()
{
if (left < maxLeftCycles && !isMoving)
{
desiredPos = transform.position + Vector3.left * 1.52f;
isMoving = true;
left++;
}
if (right < maxRightCycles && !isMoving)
{
desiredPos = transform.position - Vector3.right * 1.52f;
isMoving = true;
right++;
}
if (isMoving)
{
transform.position = Vector3.MoveTowards(transform.position, desiredPos, moveSpeed * Time.deltaTime);
// this == is true if the difference between both
// vectors is smaller than 0.00001
if (transform.position == desiredPos)
{
isMoving = false;
transform.position = desiredPos;
}
}
}
I put Debug.Log in this code and in vector3.right and left but it never get triggered.
if (Input.GetKeyUp(KeyCode.RightArrow) ||
Swipe.swipe == Swipe.SwipeDirection.right)
{
Debug.Log("This is traacked");
Swipe.ResetSwipe();
right = 0;
}
if (Input.GetKeyUp(KeyCode.LeftArrow) ||
Swipe.swipe == Swipe.SwipeDirection.left)
{
Debug.Log("This is traacked");
Swipe.ResetSwipe();
left = 0;
}
This is the code for Swipe script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Swipe : MonoBehaviour
{
private float fingerStartTime = 0.0f;
private Vector2 fingerStartPos = Vector2.zero;
private bool isSwipe = false;
private float minSwipeDist = 50.0f;
private float maxSwipeTime = 0.5f;
public enum SwipeDirection
{
none,
up,
down,
right,
left
}
public static SwipeDirection swipe;
void Start()
{
swipe = SwipeDirection.none;
}
public static void ResetSwipe()
{
swipe = SwipeDirection.none;
}
// Update is called once per frame
void Update()
{
if (Input.touchCount > 0)
{
foreach (Touch touch in Input.touches)
{
switch (touch.phase)
{
case TouchPhase.Began:
/* this is a new touch */
isSwipe = true;
fingerStartTime = Time.time;
fingerStartPos = touch.position;
break;
case TouchPhase.Canceled:
/* The touch is being canceled */
isSwipe = false;
break;
case TouchPhase.Ended:
float gestureTime = Time.time - fingerStartTime;
float gestureDist = (touch.position - fingerStartPos).magnitude;
if (isSwipe && gestureTime < maxSwipeTime && gestureDist > minSwipeDist)
{
Vector2 direction = touch.position - fingerStartPos;
Vector2 swipeType = Vector2.zero;
if (Mathf.Abs(direction.x) > Mathf.Abs(direction.y))
{
// the swipe is horizontal:
swipeType = Vector2.right * Mathf.Sign(direction.x);
}
else
{
// the swipe is vertical:
swipeType = Vector2.up * Mathf.Sign(direction.y);
}
if (swipeType.x != 0.0f)
{
if (swipeType.x > 0.0f)
{
// MOVE RIGHT
swipe = SwipeDirection.right;
}
else
{
// MOVE LEFT
swipe = SwipeDirection.left;
}
}
if (swipeType.y != 0.0f)
{
if (swipeType.y > 0.0f)
{
// MOVE UP
swipe = SwipeDirection.up;
}
else
{
// MOVE DOWN
swipe = SwipeDirection.down;
}
}
}
break;
}
}
}
}
}
The code in Update method for swipe input which I debug never get called or never work for me.I can not understand what i am doing wrong because the same code actually works in my previous game.
Thank you so much for reading my question I hope there will be some guy who can help me to solve this issue.
If it worked as is before hand in another project I would make sure that you are attaching the script to a game object. If it is attached to a game object make sure that it is not marked as inactive and that you aren't turning the object to inactive somewhere else in your scripts.
If neither of these are the case I would also try removing the script from the object and then reattaching it, and if that still doesn't work try deleting the object the script is attached to (if possible) and then recreate it and reattach the script.
EDIT Full Scripts:
SoldierController Script (removed few variables due to character limitaton). I have declared 1 new variable called DontMove and want this to be called from the ElevatorOpen script. Issue I am having is calling this script even though this is set to static and public.
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]
public class SoldierController : MonoBehaviour
{
#region Variables
public Transform gunPoint;
public GameObject bulletPrefab;
//Components
protected Animator animator;
private GameObject camera;
private Camera cam;
public GameObject splashFX;
public AudioClip gunShotSound;
//action variables
public static bool dontMove = false;
public float walkSpeed = 1.35f;
bool canwalk = true;
float moveSpeed;
public float runSpeed = 1f;
public float rotationSpeed = 20f;
bool isMoving = false;
public bool walking = true;
bool areWalking;
Vector3 newVelocity;
Vector3 inputVec;
//aiming/shooting variables
bool canAim;
bool canFire = true;
public bool aiming = true;
bool isAiming = false;
public bool grenading = true;
bool isGrenading;
bool canGrenade = true;
int weaponType = 0;
//Weapon Prefabs
GameObject pistol;
GameObject rifle;
GameObject launcher;
GameObject heavy;
#endregion
#region Initialization
void Start()
{
canMove = true;
//dontMove = false;
//set the animator component
animator = GetComponentInChildren<Animator>();
//sets the weight on any additional layers to 1
if (animator.layerCount >= 2)
{
animator.SetLayerWeight(1, 1);
}
//Get the camera
camera = GameObject.FindGameObjectWithTag("MainCamera");
cam = camera.GetComponent<Camera>();
//sets the Weapon to 1 in the animator
weaponType = 1;
StartCoroutine(COSwitchWeapon("Weapon", 1));
}
#endregion
#region Update
void Update()
{
x = Input.GetAxisRaw("Horizontal");
//z = Input.GetAxisRaw("Vertical");
inputVec = new Vector3(x, 0, z);
if (animator)
{
CoverUpdate();
JumpingUpdate();
if (!isSwimming) //character can't do any actions while swimming
{
if (Input.GetKeyDown(KeyCode.LeftControl) && canFire && cover != 1 && covering)
{
Fire();
}
if (Input.GetMouseButtonDown(0) && canFire && cover != 1 && covering)
{
Fire();
}
if (Input.GetButton("Fire2") && canAim && aiming)
{
isAiming = true;
}
else
{
isAiming = false;
}
}
}
}
#endregion
#region Fixed/Late Updates
void FixedUpdate()
{
CheckForGrounded();
if (!isSwimming) //character is not swimming
{
//gravity
GetComponent<Rigidbody>().AddForce(0, gravity, 0, ForceMode.Acceleration);
if (aircontrol)
AirControl();
//check if we aren't in cover and can move
if (!covered && canMove)
{
if (canPushPull)
{
if (!isPushPulling)
moveSpeed = UpdateMovement(); //if we are not pushpull use normal movement speed
else
moveSpeed = PushPull(); //we are push pulling, use pushpullspeed
}
else
moveSpeed = UpdateMovement();
}
}
else //character is swimming
{
moveSpeed = Swimming();
}
}
void LateUpdate()
{
//Get local velocity of charcter
float velocityXel = transform.InverseTransformDirection(GetComponent<Rigidbody>().velocity).x;
float velocityZel = transform.InverseTransformDirection(GetComponent<Rigidbody>().velocity).z;
//Update animator with movement values
animator.SetFloat("Velocity X", velocityXel / runSpeed);
animator.SetFloat("Velocity Z", velocityZel / runSpeed);
//if we are moving, set our animator
if (moveSpeed > 0)
{
isMoving = true;
animator.SetBool("Moving", true);
}
else
{
isMoving = false;
animator.SetBool("Moving", false);
}
}
#endregion
void RotateTowardsMovementDir()
{
// Rotation
if (inputVec != Vector3.zero && !isAiming)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(inputVec), Time.deltaTime * rotationSpeed);
}
}
#region UpdateMovement
float UpdateMovement()
{
Vector3 motion = inputVec;
if (isGrounded)
{
//reduce input for diagonal movement
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//apply velocity based on platform speed to prevent sliding
float platformVelocity = platformSpeed.magnitude * .4f;
Vector3 platformAdjust = platformSpeed * platformVelocity;
//set speed by walking / running
if (areWalking)
{
canAim = false;
//check if we are on a platform and if its animated, apply the platform's velocity
if (!platformAnimated)
{
newVelocity = motion * walkSpeed + platformAdjust;
}
else
{
newVelocity = motion * walkSpeed + platformAdjust;
}
}
else
{
//check if we are on a platform and if its animated, apply the platform's velocity
if (!platformAnimated)
{
newVelocity = motion * runSpeed + platformAdjust;
}
else
{
newVelocity = motion * runSpeed + platformSpeed;
}
}
}
else
{
//if we are falling use momentum
newVelocity = GetComponent<Rigidbody>().velocity;
}
// limit velocity to x and z, by maintaining current y velocity:
newVelocity.y = GetComponent<Rigidbody>().velocity.y;
GetComponent<Rigidbody>().velocity = newVelocity;
if (!isAiming)
RotateTowardsMovementDir();
//if the right mouse button is held look at the mouse cursor
if (isAiming)
{
//make character point at mouse
Quaternion targetRotation;
float rotationSpeed = 40f;
Vector3 mousePos = Input.mousePosition;
mousePos = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.transform.position.y - transform.position.y));
targetRotation = Quaternion.LookRotation(mousePos - new Vector3(transform.position.x, 0, transform.position.z));
transform.eulerAngles = Vector3.up * Mathf.MoveTowardsAngle(transform.eulerAngles.y, targetRotation.eulerAngles.y, (rotationSpeed * Time.deltaTime) * rotationSpeed);
}
//calculate the rolling time
rollduration -= rolldamp;
if (rollduration > 0)
{
isRolling = true;
}
else
{
isRolling = false;
}
if (isRolling)
{
Vector3 localforward = transform.TransformDirection(0, 0, 1);
GetComponent<Rigidbody>().velocity = localforward * rollSpeed;
}
//return a movement value for the animator
return inputVec.magnitude;
}
#endregion
#region AirControl
void AirControl()
{
float x = Input.GetAxisRaw("Horizontal");
float z = Input.GetAxisRaw("Vertical");
Vector3 inputVec = new Vector3(x, 0, z);
Vector3 motion = inputVec;
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//allow some control the air
GetComponent<Rigidbody>().AddForce(motion * inAirSpeed, ForceMode.Acceleration);
//limit the amount of velocity we can achieve
float velocityX = 0;
float velocityZ = 0;
if (GetComponent<Rigidbody>().velocity.x > maxVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - maxVelocity;
if (velocityX < 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.x < minVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - minVelocity;
if (velocityX > 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z > maxVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - maxVelocity;
if (velocityZ < 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z < minVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - minVelocity;
if (velocityZ > 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
}
#endregion
#region Swimming
float Swimming()
{
Vector3 motion = inputVec;
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//movement is using swimSpeed
GetComponent<Rigidbody>().AddForce(motion * swimSpeed, ForceMode.Acceleration);
//limit the amount of velocity we can achieve
float velocityX = 0;
float velocityZ = 0;
if (GetComponent<Rigidbody>().velocity.x > maxVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - maxVelocity;
if (velocityX < 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.x < minVelocity)
{
velocityX = GetComponent<Rigidbody>().velocity.x - minVelocity;
if (velocityX > 0)
velocityX = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(-velocityX, 0, 0), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z > maxVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - maxVelocity;
if (velocityZ < 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
if (GetComponent<Rigidbody>().velocity.z < minVelocity)
{
velocityZ = GetComponent<Rigidbody>().velocity.z - minVelocity;
if (velocityZ > 0)
velocityZ = 0;
GetComponent<Rigidbody>().AddForce(new Vector3(0, 0, -velocityZ), ForceMode.Acceleration);
}
RotateTowardsMovementDir();
//return a movement value for the animator
return inputVec.magnitude;
}
#endregion
#region PushPull
float PushPull()
{
//set bools
canAim = false;
canAbility = false;
canCover = false;
canFire = false;
canGrenade = false;
canItem = false;
canJump = false;
canMelee = false;
canReload = false;
canRoll = false;
canSignal = false;
canwalk = false;
isPushPulling = true;
animator.SetBool("PushPull", true);
Vector3 motion = inputVec;
//reduce input for diagonal movement
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1) ? .7f : 1;
//movement is using pushpull speed
GetComponent<Rigidbody>().velocity = motion * pushPullSpeed;
//return a movement value for the animator
return inputVec.magnitude;
}
#endregion
#region Grounding
void CheckForGrounded()
{
float distanceToGround;
float threshold = .45f;
RaycastHit hit;
Vector3 offset = new Vector3(0, .4f, 0);
if (Physics.Raycast((transform.position + offset), -Vector3.up, out hit, 100f))
{
distanceToGround = hit.distance;
if (distanceToGround < threshold)
{
isGrounded = true;
//moving platforms
if (hit.transform.tag == "Platform")
{
//get platform script from collided platform
Platform platformScript = hit.transform.GetComponent<Platform>();
//check if the platform is moved with physics or if it is animated and get velocity from it
if (platformScript.animated)
{
platformSpeed = platformScript.velocity;
platformAnimated = true;
}
if (!platformScript.animated)
{
platformSpeed = hit.transform.GetComponent<Rigidbody>().velocity;
}
//get the platform rotation to pass into our character when they are on a platform
platformFacing = hit.transform.rotation;
}
else
{
//if we are not on a platform, reset platform variables
platformSpeed = new Vector3(0, 0, 0);
platformFacing.eulerAngles = new Vector3(0, 0, 0);
Platform platformScript = null;
float platformVelocity = 0f;
}
}
else
{
isGrounded = false;
}
}
}
#endregion
#region Cover
void CoverUpdate()
{
/*
if (covering && !isSwimming)
{
//check if we press cover button
if (Input.GetButtonDown("Cover") && canCover && !covered)
{
//set variables
animator.SetBool("Moving", false);
Input.ResetInputAxes();
isMoving = false;
animator.SetBool("Moving", false);
covered = true;
canReload = true;
canCover = false;
canItem = false;
canMelee = false;
canFire = false;
canItem = false;
canGrenade = false;
canJump = false;
cover = 1;
animator.SetInteger("Cover", 1);
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
}
else
{
//if we are already in cover and press the cover button, get out of cover
if (Input.GetButtonDown("Cover") && covered == true)
{
//set the animation back to idle
animator.SetInteger("Cover", 3);
//set variables
cover = 0;
covered = false;
canCover = true;
canAbility = true;
canAim = true;
canItem = true;
canGrenade = true;
canFire = true;
}
}
}*/
}
#endregion
#region Jumping
void JumpingUpdate()
{
if (!isSwimming) //if character is not swimming
{
//If the character is on the ground
if (isGrounded)
{
//set the animation back to idle
animator.SetInteger("Jumping", 0);
//set variables
jumped = false;
//check if we press jump button
if (canJump && Input.GetButtonDown("Jump") && cover != 1)
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity += jumpSpeed * Vector3.up;
//set variables
animator.SetTrigger("Jump");
animator.SetInteger("Jumping", 2);
}
}
else
{
//set bools
canDoubleJump = true;
if (!falling && !jumped)
{
//set the animation back to idle
animator.SetInteger("Jumping", 2);
falling = true;
}
//if double jumping is allowed and jump is pressed, do a double jump
if (canDoubleJump && doublejumping && Input.GetButtonDown("Jump") && doublejumped != true && doublejumping)
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity += doublejumpSpeed * Vector3.up;
//set the animation to double jump
animator.SetInteger("Jumping", 3);
//set variables
canJump = false;
doublejumped = true;
isJumping = true;
falling = false;
jumped = false;
}
}
}
else //characer is swimming
{
//check if we press jump button
if (canSwim && Input.GetButtonDown("Jump"))
{
if (x != 0 || z != 0) //if the character movement input is not 0, swim in facing direction
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity += swimBurstSpeed * transform.forward;
animator.SetTrigger("SwimBurst");
}
else //we are not trying to move the character, jump up
{
// Apply the current movement to launch velocity
GetComponent<Rigidbody>().velocity = jumpSpeed * Vector3.up;
//set variables
animator.SetTrigger("Jump");
canJump = false;
isJumping = true;
canDoubleJump = true;
jumped = true;
animator.SetInteger("Jumping", 2);
}
}
}
}
#endregion
#region Misc Methods
void Rolling()
{
StartCoroutine(COPlayOneShot("Rolling"));
covered = false;
canCover = false;
cover = 0;
animator.SetInteger("Cover", 0);
isRolling = true;
}
void Fire()
{
StartCoroutine(COPlayOneShot("Fire"));
(Instantiate(bulletPrefab, gunPoint.position, transform.root.rotation) as GameObject).GetComponent<BulletController>().damage = 20;
StartCoroutine(WeaponCooldown());
GetComponent<AudioSource>().PlayOneShot(gunShotSound);
}
IEnumerator WeaponCooldown()
{
canFire = false;
yield return new WaitForSeconds(0.1f);
canFire = true;
}
void Ability()
{
StartCoroutine(COPlayOneShot("Ability"));
}
void Item()
{
StartCoroutine(COPlayOneShot("Item"));
}
void Grenade()
{
StartCoroutine(COGrenade());
isGrenading = true;
}
void Reload()
{
StartCoroutine(COReload(weaponType));
isReloading = true;
}
void Signal()
{
StartCoroutine(COPlayOneShot("Signal"));
}
void Melee()
{
StartCoroutine(COMelee());
isMelee = true;
}
void Pain()
{
StartCoroutine(COPlayOneShot("Pain"));
}
//plays a random death# animation between 1-3
void Death()
{
//stop character movement
animator.SetBool("Moving", true);
Input.ResetInputAxes();
isMoving = false;
int deathnumber = 5;
animator.SetInteger("Death", deathnumber);
}
#endregion
#region CORoutines
//function to play a one shot animation
public IEnumerator COPlayOneShot(string paramName)
{
animator.SetBool(paramName, true);
yield return null;
animator.SetBool(paramName, false);
}
//function to switch weapons
public IEnumerator COSwitchWeapon(string weaponname, int weaponnumber)
{
//sets Weapon to 0 first to reset
animator.SetInteger(weaponname, 0);
yield return null;
yield return null;
animator.SetInteger(weaponname, weaponnumber);
}
//function to reload
public IEnumerator COReload(int weapon)
{
//sets Weapon to 0 first to reset
animator.SetBool("Reload", true);
yield return null;
animator.SetBool("Reload", false);
float wait = 0;
if (weaponType == 1 || weaponType == 2)
{
wait = 1.85f;
}
if (weaponType == 3 || weaponType == 4)
{
wait = 3f;
}
yield return new WaitForSeconds(wait);
isReloading = false;
}
//function to grenade
IEnumerator COGrenade()
{
//sets Weapon to 0 first to reset
animator.SetBool("Grenade", true);
yield return null;
animator.SetBool("Grenade", false);
yield return new WaitForSeconds(1);
isGrenading = false;
}
//function to Melee
IEnumerator COMelee()
{
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
canMove = false;
isMoving = false;
animator.SetTrigger("Melee");
yield return new WaitForSeconds(.7f);
isMelee = false;
canMove = true;
}
IEnumerator COKnockback()
{
StartCoroutine(COPlayOneShot("Knockback"));
return null;
}
public IEnumerator CODazed()
{
StartCoroutine(COPlayOneShot("Dazed"));
Debug.Log("Cant Move");
canMove = false;
canFire = false;
canAim = false;
canJump = false;
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
yield return new WaitForSeconds(3.0f);
GetComponent<Rigidbody>().velocity = new Vector3(0, 0, 0);
canMove = true;
canFire = true;
canAim = true;
canJump = true;
}
#endregion
#region WeaponSwitching
void WeaponSwitch()
{
weaponType++;
if (weaponType == 1)
{
//enables pistol, disables other weapons
pistol.SetActive(true);
rifle.SetActive(false);
launcher.SetActive(false);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 1));
}
if (weaponType == 2)
{
//enables rifle, disables other weapons
pistol.SetActive(false);
rifle.SetActive(true);
launcher.SetActive(false);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 2));
}
if (weaponType == 3)
{
//enables launcher, disables other weapons
pistol.SetActive(false);
rifle.SetActive(false);
launcher.SetActive(true);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 3));
}
if (weaponType == 4)
{
//enables heavy, disables other weapons
pistol.SetActive(false);
rifle.SetActive(false);
launcher.SetActive(false);
heavy.SetActive(true);
StartCoroutine(COSwitchWeapon("Weapon", 4));
}
if (weaponType == 5)
{
//enables pistol, disables other weapons
pistol.SetActive(true);
rifle.SetActive(false);
launcher.SetActive(false);
heavy.SetActive(false);
StartCoroutine(COSwitchWeapon("Weapon", 1));
weaponType = 1;
}
}
#endregion
}
And finally the elevatorOPen script:
using UnityEngine;
using System.Collections;
public class ElevatorOpen : MonoBehaviour
{
private Animator animator;
public AudioClip ElevatorBing;
void Awake ()
{
animator = GetComponent <Animator>();
}
void OnTriggerEnter (Collider other)
{
if (other.gameObject.tag == "Player") {
animator.SetInteger ("Open", 1);
GetComponent<AudioSource>().PlayOneShot(ElevatorBing);
}
}
void OnTriggerExit (Collider other)
{
if (other.gameObject.tag == "Player") {
animator.SetInteger ("Open", 0);
SoldierController.dontMove = true;
}
}
}
This has been addressed. This is a bug with Unity 5 Beta - Spoke to a member of staff who provided me the latest version of Unity, which has fixed the issue.
I am beginner of C# unity. I was searching the solution to swap cube with add force in 8 direction, but I could not find anything. I am really confused that how can I do this. Someone please guide me in this regard. Any code example or tutorial for solving the problem will be appreciated.
Thanks in advance.
Here is my code:
using UnityEngine;
using System.Collections;
public class Swaping1 : MonoBehaviour {
int swipeIndex = -1; //index of first detected swipe to prevent multiple swipes
public Vector2 startPos; //starting position of touch
public float minSwipeDist;
public float UpSwape;
public float DownSwape;
public float LeftSwape;
public float RightSwape;
public GUIButtons GUIButtonsObj;
// Use this for initialization
void Start () {
GUIButtonsObj=GetComponent<GUIButtons>();
}
public void swipe()
{
for (int i = 0; i < Input.touchCount; i++) {
Touch touch = Input.touches [i];
switch (touch.phase) {
case TouchPhase.Began:
if (swipeIndex == -1) {
swipeIndex = i;
startPos = touch.position;
}
break;
case TouchPhase.Moved:
if (i != swipeIndex)
break;
Vector2 direction = touch.position - startPos;
//vertical swipe
if (Mathf.Abs (direction.x) < Mathf.Abs (direction.y)) {
//swipe up
if ((touch.position.y - startPos.y) > minSwipeDist) {
//GUIButtonsObj.UpButton();
//transform.Translate(0f, UpSwape, 0f);
swipeIndex = -1;
}
//swipe down
else if ((touch.position.y - startPos.y) < -minSwipeDist) {
//transform.Translate(0f, -DownSwape, 0f);
//GUIButtonsObj.DownButton();
swipeIndex = -1;
}
}
//horizontal swipe
else {
//swipe right
if ((touch.position.x - startPos.x) < -minSwipeDist) {
//transform.Translate(-RightSwape, 0f, 0f);
GUIButtonsObj.LeftButton();
swipeIndex = -1;
}
//swipe left
else if ((touch.position.x - startPos.x) > minSwipeDist) {
// transform.Translate(LeftSwape, 0f, 0f);
GUIButtonsObj.RightButton();
swipeIndex = -1;
}
}
break;
}
}
}
// Update is called once per frame
void Update ()
{
swipe ();
}
}
Ok, Try this, if it works for you.
using UnityEngine;
public enum Swipes { None, Up, Down, Left, TopLeft, BottomLeft, Right, TopRight, BottomRight};
public class SwipeManager : MonoBehaviour
{
public float minSwipeLength = 200f;
Vector2 currentSwipe;
private Vector2 fingerStart;
private Vector2 fingerEnd;
public static Swipes direction;
void Update ()
{
SwipeDetection();
}
public void SwipeDetection ()
{
if (Input.GetMouseButtonDown(0)) {
fingerStart = Input.mousePosition;
fingerEnd = Input.mousePosition;
}
if(Input.GetMouseButton(0)) {
fingerEnd = Input.mousePosition;
currentSwipe = new Vector2 (fingerEnd.x - fingerStart.x, fingerEnd.y - fingerStart.y);
// Make sure it was a legit swipe, not a tap
if (currentSwipe.magnitude < minSwipeLength) {
direction = Swipes.None;
return;
}
float angle = (Mathf.Atan2(currentSwipe.y, currentSwipe.x) / (Mathf.PI));
Debug.Log(angle);
// Swipe up
if (angle>0.375f && angle<0.625f) {
direction = Swipes.Up;
Debug.Log ("Up");
// Swipe down
} else if (angle<-0.375f && angle>-0.625f) {
direction = Swipes.Down;
Debug.Log ("Down");
// Swipe left
} else if (angle<-0.875f || angle>0.875f) {
direction = Swipes.Left;
Debug.Log ("Left");
// Swipe right
} else if (angle>-0.125f && angle<0.125f) {
direction = Swipes.Right;
Debug.Log ("Right");
}
else if(angle>0.125f && angle<0.375f){
direction = Swipes.TopRight;
Debug.Log ("top right");
}
else if(angle>0.625f && angle<0.875f){
direction = Swipes.TopLeft;
Debug.Log ("top left");
}
else if(angle<-0.125f && angle>-0.375f){
direction = Swipes.BottomRight;
Debug.Log ("bottom right");
}
else if(angle<-0.625f && angle>-0.875f){
direction = Swipes.BottomLeft;
Debug.Log ("bottom left");
}
}
if(Input.GetMouseButtonUp(0)) {
direction = Swipes.None;
}
}
}