Hello, I’m making a platformer, where you are jumping every time you touch a platform and you can drag your character with touch position. The problem is I’m using rigidbody’s movePosition method to drag the player, but this affects the velocity that I’m setting, so my character could Jump. Every time I try to drag my player - the velocity.y freezes it’s value as the last one before starting to drag. Any solutions?
Share your code sample you are using to perform these functionality. to rectify your problem.
Here is my code, attached to the player:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float bounceForce;
private GameObject player;
private Rigidbody2D rb;
private Vector3 pos;
private Vector3 v3P1;
private bool movePlayer1;
private bool draggingP1;
private Ray ray;
private RaycastHit2D hit;
private Transform toDrag;
void Start()
{
player = this.gameObject;
rb = player.GetComponent<Rigidbody2D>();
draggingP1 = false;
toDrag = gameObject.transform;
}
private void Update()
{
pos = Input.mousePosition;
ray = Camera.main.ScreenPointToRay(pos);
if (Input.GetMouseButtonDown(0))
{
hit = Physics2D.Raycast(ray.origin, ray.direction, Mathf.Infinity);
if (hit && (hit.collider.tag == "Player1"))
{
//toDrag = hit.transform;
//dist = hit.transform.position.z - Camera.main.transform.position.z;
v3P1 = new Vector3(ray.origin.x, toDrag.position.y, 0);
v3P1 = Camera.main.ScreenToWorldPoint(v3P1);
//offset = toDrag.position - v3;
draggingP1 = true;
}
}
if (Input.GetMouseButton(0) && draggingP1)
{
movePlayer1 = true;
v3P1 = new Vector3(ray.origin.x, toDrag.position.y, 0);
//rb.MovePosition(v3);
}
if (Input.GetMouseButtonUp(0) && draggingP1)
{
movePlayer1 = false;
draggingP1 = false;
}
}
private void FixedUpdate()
{
if (movePlayer1)
{
rb.MovePosition(v3P1);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.relativeVelocity.y > 0f)
{
if (collision.gameObject.tag == "Platform")
{
Vector2 velocity = rb.velocity;
velocity.y = bounceForce;
rb.velocity = velocity;
}
}
}
}