Model doesn't move in touch direction - unity3d

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);
}

Related

Dashing in Unity 3D using Rigidbody

im currently making a fps game and i have a rigidbody character controller and im trying to make it dash towards the direction the player is facing however my current dash function makes it go downwards and goes very fast
any ideas for how i can either fix the dashing or make a new dash mechanism?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement : MonoBehaviour
{
float yaw = 0f, pitch = 0f;
Rigidbody rb;
public float walkSpeed = 5f, sensitivity = 2f;
bool jumping = false;
private float DashDistance = 5f;
private void Start()
{
Cursor.lockState = CursorLockMode.Locked;
rb = GetComponent<Rigidbody>();
}
private void Update()
{
if (Input.GetKey(KeyCode.Space) && Physics.Raycast(rb.transform.position, Vector3.down, 1 + 0.001f))
rb.velocity = new Vector3(rb.velocity.x, 5f, rb.velocity.z);
if (Physics.Raycast(rb.transform.position, Vector3.down, 1 + 0.001f))
jumping = false;
else
jumping = true;
if (jumping && Input.GetKey(KeyCode.LeftControl))
Dash();
Look();
}
private void FixedUpdate()
{
Movement();
}
void Look()
{
pitch -= Input.GetAxisRaw("Mouse Y") * sensitivity;
pitch = Mathf.Clamp(pitch, -90f, 90f);
yaw += Input.GetAxisRaw("Mouse X") * sensitivity;
Camera.main.transform.localRotation = Quaternion.Euler(pitch, yaw, 0f);
}
void Movement()
{
Vector2 axis = new Vector2(Input.GetAxis("Vertical"), Input.GetAxis("Horizontal")) * walkSpeed;
Vector3 forward = new Vector3(-Camera.main.transform.right.z, 0f, Camera.main.transform.right.x);
Vector3 wishDir = (forward * axis.x + Camera.main.transform.right * axis.y + Vector3.up * rb.velocity.y);
rb.velocity = wishDir;
}
void Dash()
{
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 1f, Input.GetAxis("Vertical"));
Vector3 offset = new Vector3(movement.x * transform.position.x, movement.y * transform.position.y, movement.z * transform.position.z);
rb.AddForce(transform.position + (offset * DashDistance), ForceMode.VelocityChange);
}
}
I think you should add force in the forward direction.
AddForce(transform.forward * yourForceValue);

How to make my stick rotating after bouncing with button long pressed?

Basically I want to make bouncing stick and rotate control, with the left-right button.i'm facing an issue that the rotate not good as I expected because it won't follow my button like being affected by something after bouncing,
I'm using 2d physics material with friction = 1 and Bounciness = 0.9797 for perfect bouncing also attached to rigidbody2d.
I don't know, should I attach it on collider?
here my Player control Script:
public Rigidbody2D r2d;
public float vertical;
public float horizontal;
public Joystick joystick;
private void Start() {
r2d = gameObject.GetComponent < Rigidbody2D > ();
joystick = FindObjectOfType < Joystick > ();
}
private void Update() {
Movement();
}
public void Movement() {
r2d.velocity = r2d.velocity.normalized * 7f;
//horizontal = joystick.Horizontal;
//vertical = joystick.Vertical;
//if (horizontal == 0 && vertical == 0)
//{
// Vector3 curRot = transform.localEulerAngles;
// Vector3 homeRot = transform.localEulerAngles;
// transform.localEulerAngles = Vector3.Slerp(curRot, homeRot, Time.deltaTime * 2);
//}
//else
//{
// transform.localEulerAngles = new Vector3(0f, 0f, Mathf.Atan2(horizontal, vertical) * -180 / Mathf.PI);
//}
}
public Vector3 target;
public float rotationSpeed = 10f;
public float offset = 5;
public void turnLeft() {
Vector3 dir = target - transform.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.Euler(new Vector3(0, 0, angle + offset));
transform.rotation = Quaternion.Slerp(transform.rotation, -rotation, rotationSpeed * Time.deltaTime);
}
public void turnRight() {
Vector3 dir = target - transform.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
Quaternion rotation = Quaternion.Euler(new Vector3(0, 0, angle + offset));
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, rotationSpeed * Time.deltaTime);
}
Whenever there is a Rigidbody/Rigidbody2D involved you do not want to manipulate anything via the .transform component!
This breaks the physics, collision detection and leads to strange movements basically the transform "fighting" against physics for priority.
What you rather want to do would be e.g. adjusting the Rigidbody2D.angularVelocity
public void turnLeft()
{
// Note that Time.deltaTime only makes sense if this is actually called every frame!
r2d.angularVelocity -= rotationSpeed * Time.deltaTime;
}
public void turnRight()
{
r2d.angularVelocity += rotationSpeed * Time.deltaTime;
}

How can I match my animation with transform in Unity3d?

I have implemented a player movement and jump in my game. I also attached a run and jump animation to animator. However, the jump animation does not perfectly match with the player vertical movement. How can I match them perfectly?
Thanks in advance,
void Control()
{
if (charController.isGrounded)
{
float h = Joystick.GetHorizontalAxis("MyJoystick");
float v = Joystick.GetVerticalAxis("MyJoystick");
moveDirection = new Vector3(h, 0.0f, v);
moveDirection *= (speed * sprint);
anim.SetFloat("WalkSpeed", moveDirection.magnitude);
if (moveDirection.magnitude > 0.5)
{
anim.SetFloat("WalkSpeed", moveDirection.magnitude / speed);
anim.SetFloat("Walk", 1.0f);
transform.forward = moveDirection;
}
else if (moveDirection.magnitude > 0 && moveDirection.magnitude < 0.5)
{
anim.SetFloat("WalkSpeed", moveDirection.magnitude / (speed * 0.5f));
anim.SetFloat("Walk", 0.5f);
transform.forward = moveDirection;
}
else if (moveDirection.magnitude == 0)
{
anim.SetFloat("Walk", 0f);
}
if (Input.GetKeyDown("space"))
{
moveDirection.y = jumpSpeed;
anim.SetTrigger("Jump");
}
}
moveDirection.y -= gravity * Time.deltaTime;
charController.Move(moveDirection * Time.deltaTime);
}
There is an option in the Animator component to do what you want.
Here is a link that describes it in more details.

Lerp to target position, but only within a radius

I am making a 3D game but my player can only move on the X and Y axis. I have a player with an attached camera following my mouse, but I only want it to follow up to a max radius distance from Vector3.zero, even if my mouse is beyond those bounds.
I have tried repositioning the player to the max distance on radius every frame it tries to follow the mouse outside its bounds, but this causes camera jitters even in LateUpdate.
void LateUpdate()
{
if (Input.GetMouseButtonDown(0)) {
firstTouchPos = movementCam.ScreenPointToRay(Input.mousePosition);
playerPos = transform.position;
}
if (Input.GetMouseButton(0)) {
Ray currentTouchPos = movementCam.ScreenPointToRay(Input.mousePosition);
Vector2 direction = currentTouchPos.origin - firstTouchPos.origin;
float distance = Vector3.Distance(transform.position, Vector3.zero);
if (distance >= radius) {
targetPosition = direction.normalized * radius;
} else {
targetPosition = playerPos + direction * touchSensitivity;
}
}
transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * followSpeed);
}
I'm thinking there must be a way to clamp the positioning of the player to a radius so that I don't have to "leash" him back by repositioning him through code every frame.
You should try using Vector3.ClampMagnitude().
The solution was to use Clamp Magnitude.
void LateUpdate()
{
if (Input.GetMouseButtonDown(0)) {
firstTouchPos = movementCam.ScreenPointToRay(Input.mousePosition);
playerPos = transform.position;
}
if (Input.GetMouseButton(0)) {
// targetPosition will follow finger movements
Ray currentTouchPos = movementCam.ScreenPointToRay(Input.mousePosition);
Vector2 direction = currentTouchPos.origin - firstTouchPos.origin;
targetPosition = playerPos + direction * touchSensitivity;
}
transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * followSpeed);
transform.position = Vector3.ClampMagnitude(transform.position, radius);
}

Moving player in Subway Surf like game using left/right swipe

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!