I am developing endless runner game like subway surfer in Unity.
I want to move my player, smoothly on swipe left or right.
How can do it?
Here is my code:
using UnityEngine;
using System.Collections;
public class SwipeScript3 : MonoBehaviour {
private Touch initialTouch = new Touch();
private float distance = 0;
private bool hasSwiped = false;
//Quaternion targetx = Quaternion.Euler(0, -3f, 0);
//Quaternion targety = Quaternion.Euler(0, 3f, 0);
void FixedUpdate()
{
foreach(Touch t in Input.touches)
{
if (t.phase == TouchPhase.Began)
{
initialTouch = t;
}
else if (t.phase == TouchPhase.Moved && !hasSwiped)
{
float deltaX = initialTouch.position.x - t.position.x;
float deltaY = initialTouch.position.y - t.position.y;
distance = Mathf.Sqrt((deltaX * deltaX) + (deltaY * deltaY));
bool swipedSideways = Mathf.Abs(deltaX) > Mathf.Abs(deltaY);
if (distance > 50f)
{
if (swipedSideways && deltaX > 0) //swiped left
{
//transform.rotation = Quaternion.Slerp (transform.rotation, targetx, Time.deltaTime * 0.8f);
this.transform.Rotate(new Vector3(0, -3f, 0)*Time.deltaTime);
//transform.position = Vector3.Lerp (transform.position,new Vector3(transform.position.x+5f,transform.position.y,transform.position.z),Time.deltaTime*2f );
transform.position = Vector3.Lerp (transform.position, new Vector3 (transform.position.x - 5f, transform.position.y, transform.position.z), Time.deltaTime * 5f);
}
else if (swipedSideways && deltaX <= 0) //swiped right
{
//transform.rotation = Quaternion.Slerp (transform.rotation, targety, Time.deltaTime * 0.8f);
this.transform.Rotate(new Vector3(0, 3f, 0)*Time.deltaTime);
//transform.position = Vector3.Lerp (transform.position, new Vector3 (transform.position.x - 5f, transform.position.y, transform.position.z), Time.deltaTime * f);
transform.position = Vector3.Lerp (transform.position,new Vector3(transform.position.x+5f,transform.position.y,transform.position.z),Time.deltaTime*5f );
}
else if (!swipedSideways && deltaY > 0) //swiped down
{
//this.transform.Rotate(new Vector3(0, 2f, 0));
transform.position = Vector3.Lerp (transform.position,new Vector3(transform.position.x,transform.position.y,transform.position.z-5f),Time.deltaTime*2f );
}
else if (!swipedSideways && deltaY <= 0) //swiped up
{
this.GetComponent<Rigidbody>().velocity = new Vector3(this.GetComponent<Rigidbody>().velocity.x, 0, this.GetComponent<Rigidbody>().velocity.z);
this.GetComponent<Rigidbody>().AddForce(new Vector3(0, 400f, 0));
Debug.Log ("Swiped Up");
}
hasSwiped = true;
}
}
else if (t.phase == TouchPhase.Ended)
{
initialTouch = new Touch();
hasSwiped = false;
}
}
}
}
You could use Vector3.Slerp(Vector3 StartPosition, Vector3 DestinationPosition, float Number)
Number is between 0 and 1 and it indicates where will be the position of your object between StartPosition and DestinationPosition.
Lets say Number = 0.0f;: your object will be at StartPosition.
If Number = 0.5f;: your object will be between StartPosition and DestinationPosition.
You need to increase the Number value from 0 to 1 when swipe action is performed.
The faster you increase the "Number" value, the faster your object will move towards Destination.
You should set you StartPosition once when the swipe action begins, not give your transform.position repeatedly in your Vector3.Slerp() function.
You can find an example here in Unity Docs.
Hope this helps! Cheers!
Related
So, I was testing my scripts and i wanted my player to jump with character controller and i am having a problem with it.
Problem
```
public CharacterController control;
public float playerSpeed;
public float jumpSpeed;
void Start()
{
playerSpeed = 6.0f;
jumpSpeed = 50;
}
void Update()
{
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
Vector3 move = new Vector3 (h, 0, v);
Vector3 velocity = move * playerSpeed;
if (control.isGrounded && Input.GetKey(KeyCode.Space))
{
velocity.y += jumpSpeed; // velocity.y = jumpSpeed; tried both
}
else
{
velocity += Physics.gravity * Time.deltaTime;
}
control.Move(velocity * Time.deltaTime);
}
}```
Here's my unity screen and code above.
The problem is when i press jump it does jump but it's position goes to 2.068, i.e it jumps to low and when gravity is activated it comes down to slow, it takes around 6 seconds to come to its initial position.
I even tried to add a parent object to it so that it may change, but it does the same to it.
if (control.isGrounded && Input.GetKey(KeyCode.Space))
{
// first just try this
velocity.y += jumpSpeed * Time.deltaTime;
}
else
{
velocity.y -= Physics.gravity * Time.deltaTime;
}
and if it is not working
Vector3 move = new Vector3 (h, 0, 0);
Vector3 jump = new Vector3 (0, 0, v);
Vector3 _velocityMove = move * playerSpeed;
Vector3 _velocityJump = jump* jumpSpeed;
if (control.isGrounded && Input.GetKey(KeyCode.Space))
{
velocity.y += _velocityJump ;//and you can add ' * Time.deltaTime '
}
else
{
velocity += Physics.gravity * Time.deltaTime;
}
control.Move(_velocityMove * Time.deltaTime);
ohk so I tweaked some of my code and instead of declaring velocity.y in the condition of if the player is grounded , i declared outside the condition and change the value of variable in condition.
velocity.y = jumpSpeed;
if (control.isGrounded && Input.GetKey(KeyCode.Space))
{
jumpSpeed = 10;
}
else
{
jumpSpeed += Physics.gravity.y * Time.deltaTime;
}
This seems to do the trick and my player can jump nicely.
Code:
private Touch touch;
public float speed;
public Animator animator;
Vector3 point = new Vector3();
Vector3 targetPos;
void Start()
{
targetPos = transform.position;
}
void Update()
{
if (Input.touchCount > 0)
{
touch = Input.GetTouch(0);
if (touch.phase == TouchPhase.Moved)
{
transform.position = new Vector3(transform.position.x + touch.deltaPosition.x * Time.deltaTime, transform.position.y, transform.position.z + touch.deltaPosition.y * Time.deltaTime);
Plane plane = new Plane(Vector3.up,transform.position);
Ray ray = Camera.main.ScreenPointToRay(touch.deltaPosition);
float point = 0f;
if (plane.Raycast(ray, out point)) targetPos = ray.GetPoint(point);
transform.LookAt(targetPos);
}
}
}
The problem is when I touch the screen the character looks in the touched direction, but when I move it forward (bottom of the screen to slightly above) it still looks towards the touch position. I want it so when it moves it faces the direction its going.
touch = Input.GetTouch(0);
if(touch.phase == TouchPhase.Moved)
{
transform.position = new Vector3(transform.position.x + touch.deltaPosition.x *
Time.deltaTime,transform.position.y,
transform.position.z + touch.deltaPosition.y * Time.deltaTime);
transform.LookAt(transform.position + touch.deltaPosition);
}
this is my code i really tried everything that i see in internet but i didnt find good solution for this problem .
i can rotate my spaceship , i can make that U turn . but i cant do those ,at the same time.
void Movements()
{
float deltaTime = Time.deltaTime;
bool isLeft = Input.GetKey(KeyCode.A);
bool isRight = Input.GetKey(KeyCode.D);
bool isTurningLeft = Input.GetKey(KeyCode.A) && Input.GetKey(KeyCode.W);
bool isTurningRight = Input.GetKey(KeyCode.D) && Input.GetKey(KeyCode.W);
if (isTurningLeft)
{
newRotation = new Quaternion(transform.localRotation.x, transform.localRotation.y, transform.localRotation.z, transform.localRotation.w);
this.newRotation *= Quaternion.Euler(0, -50, 15);
transform.localRotation = Quaternion.Slerp(transform.localRotation, newRotation, Time.deltaTime);
transform.position += transform.forward * Time.deltaTime;
print("2");
}
if (isTurningRight && Input.GetKey(KeyCode.W))
{
newRotation = new Quaternion(transform.localRotation.x, transform.localRotation.y, transform.localRotation.z, transform.localRotation.w);
this. newRotation *= Quaternion.Euler(0, 50, -15);
transform.localRotation = Quaternion.Slerp(transform.localRotation, newRotation, Time.deltaTime);
transform.position += transform.forward * Time.deltaTime;
}
if (Input.GetKey(KeyCode.W) && !isTurningRight && !isTurningLeft)
{
TargetObject = Quaternion.identity;
transform.Translate(0, 0, 20 * deltaTime);
}
I'm trying to limit the zoom value of my game to a minimum and a maximum but i can't get how to do it!
I've been trying by limiting the Y according to the zoom factor but it does not work properly, because when it reaches the limit, it starts flickering, like it hit an obstacle. I found some things that can solve this problem by using the fieldofview, but I need it to work with the Y limitations!
I also want to add a panning limit, so that the player won't be able to see the end of the map but I didn't get there yet.
Anyways, here is the code i'm using and would appreciate if someone could help!
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
class ScrollAndPinch : MonoBehaviour
{
#if UNITY_IOS || UNITY_ANDROID
public Camera Camera;
public bool Rotate;
protected Plane Plane;
public float scrollSpeed;
public float rotateSpeed;
public float zoomSpeed;
public float zoomMinY;
public float zoomMaxY;
public float camsummer;
Vector3 pos;
private Vector3 velocity = Vector3.zero;
private void Awake()
{
if (Camera == null)
Camera = Camera.main;
Rotate = true;
scrollSpeed = 50f;
rotateSpeed = 50f;
zoomSpeed = 1f;
zoomMinY = 50f;
zoomMaxY = 200f;
camsummer = 0.1f;
pos = new Vector3(0f, 0f, 0f);
}
private void Update()
{
//Update Plane
if (Input.touchCount >= 1)
Plane.SetNormalAndPosition(transform.up, transform.position);
var Delta1 = Vector3.zero;
var Delta2 = Vector3.zero;
//Scroll
if (Input.touchCount == 1)
{
Delta1 = PlanePositionDelta(Input.GetTouch(0));
if (Input.GetTouch(0).phase == TouchPhase.Moved)
Camera.transform.Translate(Delta1 * scrollSpeed * Time.deltaTime, Space.World);
}
//Pinch
if (Input.touchCount == 2)
{
var pos1 = PlanePosition(Input.GetTouch(0).position);
var pos2 = PlanePosition(Input.GetTouch(1).position);
var pos1b = PlanePosition(Input.GetTouch(0).position - Input.GetTouch(0).deltaPosition);
var pos2b = PlanePosition(Input.GetTouch(1).position - Input.GetTouch(1).deltaPosition);
//calc zoom to be done relative to the distance moved between the fingers
var zoom = (Vector3.Distance(pos1, pos2) /
Vector3.Distance(pos1b, pos2b));
//edge case (Bad calculation)
if (zoom == 0 || zoom > 10)
return;
//Move cam amount the mid ray. This is where the zoom is applied
// Vector3 pos = Camera.transform.position;
// pos.y = Mathf.Clamp(pos.y, zoomMinY, zoomMaxY);
// Camera.transform.position = Vector3.Lerp(pos1, Camera.transform.position, (1 / zoom));
// Camera.transform.position = pos;
if (Camera.transform.position.y < zoomMinY | Camera.transform.position.y > zoomMaxY)
{
// Camera.transform.position = pos;
Camera.transform.position = Vector3.SmoothDamp(Camera.transform.position, pos, ref velocity, camsummer);
// Camera.transform.position = Vector3.LerpUnclamped(Camera.transform.position, pos, camsummer);
// for (int i = 0; i < 1000; i++)
// {
// }
}
else if (Camera.transform.position.y >= zoomMinY && Camera.transform.position.y <= zoomMaxY)
{
pos = Camera.transform.position;
Camera.transform.position = Vector3.LerpUnclamped(pos1, Camera.transform.position, (1 / zoom));
//This is where the rotation is applied
if (Rotate && pos2b != pos2)
Camera.transform.RotateAround(pos1, Plane.normal,
Vector3.SignedAngle(pos2 - pos1, pos2b - pos1b, Plane.normal) * rotateSpeed * Time.deltaTime);
}
// pos.y = zoomMinY;
}
// if (Camera.transform.position.y > 200)
// {
// zoomMaxY.y = 200;
// Camera.transform.position = zoomMaxY;
// }
// else if (Camera.transform.position.y < 50)
// {
// zoomMinY.y = 50;
// Camera.transform.position = zoomMinY;
// }
// else if (Camera.transform.position.y >= 50 && Camera.transform.position.y <= 200)
// {
// Camera.transform.position = Vector3.LerpUnclamped(pos1, Camera.transform.position, (1 / zoom));
// }
// Vector3 Cam = Mathf.Clamp(Camera.transform.position.y, zoomMinY.y, zoomMaxY.y);
// if (Camera.transform.position.y > zoomMaxY || Camera.transform.position.y < zoomMinY)
// {
// Vector3 camLimit = Camera.transform.position;
// camLimit.y = Mathf.Clamp(Camera.transform.position.y, zoomMinY, zoomMaxY);
// Camera.transform.position = camLimit;
// // Vector3 camLimit = Camera.transform.position;
// // camLimit = (transform.position.);
// // Camera.transform.position = camLimit;
// }
// else if (Camera.transform.position.y >= zoomMinY && Camera.transform.position.y <= zoomMaxY)
// {
// Camera.transform.position = Vector3.LerpUnclamped(pos1, Camera.transform.position, (1 / zoom));
// }
}
protected Vector3 PlanePositionDelta(Touch touch)
{
//not moved
if (touch.phase != TouchPhase.Moved)
return Vector3.zero;
//delta: How far have we moved from A to B by sliding the finger
var rayBefore = Camera.ScreenPointToRay(touch.position - touch.deltaPosition);
var rayNow = Camera.ScreenPointToRay(touch.position);
if (Plane.Raycast(rayBefore, out var enterBefore) && Plane.Raycast(rayNow, out var enterNow))
return rayBefore.GetPoint(enterBefore) - rayNow.GetPoint(enterNow);
//not on plane
return Vector3.zero;
}
protected Vector3 PlanePosition(Vector2 screenPos)
{
//position
var rayNow = Camera.ScreenPointToRay(screenPos);
if (Plane.Raycast(rayNow, out var enterNow))
return rayNow.GetPoint(enterNow);
return Vector3.zero;
}
private void OnDrawGizmos()
{
Gizmos.DrawLine(transform.position, transform.position + transform.up);
}
#endif
}
And to make it easier to see, this is the part I am struggling to make it work.
if (Camera.transform.position.y < zoomMinY | Camera.transform.position.y > zoomMaxY)
{
Camera.transform.position = Vector3.SmoothDamp(Camera.transform.position, pos, ref velocity, camsummer);
}
else if (Camera.transform.position.y >= zoomMinY && Camera.transform.position.y <= zoomMaxY)
{
pos = Camera.transform.position;
Camera.transform.position = Vector3.LerpUnclamped(pos1, Camera.transform.position, (1 / zoom));
//This is where the rotation is applied
if (Rotate && pos2b != pos2)
Camera.transform.RotateAround(pos1, Plane.normal,
Vector3.SignedAngle(pos2 - pos1, pos2b - pos1b, Plane.normal) * rotateSpeed * Time.deltaTime);
}
Does this happen when the camera gets close to an object?
If so change the near clip plane distance on your camera to.near = 0
That should stop it from not showing the gameobject, if ur camera keeps moving it might cause the flickering because it clips in and out of the near clip plane
I have a character in Unity which use a move script, to transform its position.x, y, or z everytime when I press the appropriate button. Now I would like to change my code to just rotate the character when the user press the "a" or "d" and don't move it, however if the user press the "w" button move it forward.
I have already looked for it on the internet, and found out that I would need to use Vector3.forward somehow, but it doesn't work.
Here is my script:
This is the script which actually moves the character:
(It is attached to a Player object which contains the moveable characters)
public class Move : MonoBehaviour {
float lerpTime;
float currentLerpTime;
float perc = 1;
Vector3 startPos;
Vector3 endPos;
bool firstInput;
public bool justJump;
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("up") || Input.GetButtonDown("down") || Input.GetButtonDown("left") || Input.GetButtonDown("right")) {
if (perc == 1) {
lerpTime = 1;
currentLerpTime = 0;
firstInput = true;
justJump = true;
}
}
startPos = gameObject.transform.position;
if (Input.GetButtonDown("right") && gameObject.transform.position == endPos) {
endPos = new Vector3(transform.position.x + 0.5f, transform.position.y, transform.position.z);
}
if (Input.GetButtonDown("left") && gameObject.transform.position == endPos) {
endPos = new Vector3(transform.position.x - 0.5f, transform.position.y, transform.position.z);
}
if (Input.GetButtonDown("up") && gameObject.transform.position == endPos) {
endPos = new Vector3(transform.position.x, transform.position.y, transform.position.z + 0.5f);
}
if (Input.GetButtonDown("down") && gameObject.transform.position == endPos) {
endPos = new Vector3(transform.position.x, transform.position.y, transform.position.z - 0.5f);
}
if (firstInput == true) {
currentLerpTime += Time.deltaTime * 5;
perc = currentLerpTime / lerpTime;
gameObject.transform.position = Vector3.Lerp(startPos, endPos, perc);
if (perc > 0.8f) {
perc = 1;
}
if (Mathf.Round(perc) == 1) {
justJump = false;
}
}
}
}
And here is my "rotate script", which is attached to the moveable character(s) itself:
public class AnimationController : MonoBehaviour {
Animator anim;
public GameObject thePlayer;
// Use this for initialization
void Start () {
anim = gameObject.GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
Move moveScript = thePlayer.GetComponent<Move>();
if (moveScript.justJump == true) {
anim.SetBool("Jump", true);
}
else {
anim.SetBool("Jump", false);
}
if (Input.GetButtonDown("right")) {
gameObject.transform.rotation = Quaternion.Euler(0, 90, 0);
}
if (Input.GetButtonDown("left")) {
gameObject.transform.rotation = Quaternion.Euler(0, -90, 0);
}
if (Input.GetButtonDown("up")) {
gameObject.transform.rotation = Quaternion.Euler(0, 0, 0);
}
if (Input.GetButtonDown("down")) {
gameObject.transform.rotation = Quaternion.Euler(0, 180, 0);
}
}
}
Could you give me please any help on this? (Preferably with code, if you can :) )
Assuming you want your character to move to where it is facing, and trying not to do a lot of changes to your code, this is what could be done:
First, attach both your script directly to your movable character.
Then, change your Move script to:
public class Move : MonoBehaviour {
float lerpTime;
float currentLerpTime;
float perc = 1;
Vector3 startPos;
Vector3 endPos;
bool firstInput;
public bool justJump;
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("up") || Input.GetButtonDown("down") || Input.GetButtonDown("left") || Input.GetButtonDown("right")) {
if (perc == 1) {
lerpTime = 1;
currentLerpTime = 0;
firstInput = true;
justJump = true;
}
}
startPos = gameObject.transform.position;
if (Input.GetButtonDown("up") && gameObject.transform.position == endPos) {
endPos = transform.position + gameObject.transform.rotation * (new Vector3(0, 0, 0.5f));
}
if (Input.GetButtonDown("down") && gameObject.transform.position == endPos) {
endPos = transform.position + gameObject.transform.rotation * (new Vector3(0, 0, 0.5f));
}
if (firstInput == true) {
currentLerpTime += Time.deltaTime * 5;
perc = currentLerpTime / lerpTime;
gameObject.transform.position = Vector3.Lerp(startPos, endPos, perc);
if (perc > 0.8f) {
perc = 1;
}
if (Mathf.Round(perc) == 1) {
justJump = false;
}
}
}
}
And your AnimationController script to
public class AnimationController : MonoBehaviour {
Animator anim;
public GameObject thePlayer;
// Use this for initialization
void Start () {
anim = gameObject.GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
Move moveScript = thePlayer.GetComponent<Move>();
if (moveScript.justJump == true) {
anim.SetBool("Jump", true);
}
else {
anim.SetBool("Jump", false);
}
if (Input.GetButtonDown("right")) {
gameObject.transform.rotation = gameObject.transform.rotation * Quaternion.Euler(0, 90, 0);
}
if (Input.GetButtonDown("left")) {
gameObject.transform.rotation = gameObject.transform.rotation * Quaternion.Euler(0, 90, 0);
}
}
}
This will make your character rotate only when you press the left and right buttons, and move only when you press the up and down button.
Althought this solves your problem, this is not the best way to write scripts for your character movement.
I recommend you read more about the state machine design patter. This book by Robert Nystrom has a chapter about it and is really easy to read. Also, its free to read online :)