我想编写物理学的某些部分。我有一个轮子和一个倾斜的表面。当轮子落在表面上时,它应该沿着那个表面移动。 我知道如何在车轮落在地面上之后计算机芯的力和方向,但是在这之后车轮应该如何表现?
这是我目前的代码
using UnityEngine;
public class MyPhysics : MonoBehaviour
{
public LayerMask lMask;
public Rigidbody2D ball;
public CircleCollider2D circle;
public Vector2 gravity;
public Vector2 velocity;
public float mass = 1;
public Vector2 a;
public bool simulate = true;
private Vector2 weight;
private float radius;
// Use this for initialization
void Start()
{
radius = ball.transform.localScale.x * circle.radius;
weight = mass * gravity;
}
// Update is called once per frame
void Update()
{
if (simulate)
DoAllShit();
}
void DoAllShit()
{
a += (gravity * Time.deltaTime);
velocity = (velocity + a);
RaycastHit2D hit = Physics2D.Raycast(ball.position, velocity.normalized, velocity.magnitude + radius, lMask);
if (hit)
{
float angle = Vector2.Angle(hit.normal, velocity) - 90;
// Debug.Log("angle: " + angle);
float magnitude = velocity.magnitude * Mathf.Cos(Mathf.Deg2Rad * angle);
// Debug.Log("magnitude of velocity: " + velocity.magnitude + " magnitude of cos: " + magnitude);
Vector2 rotatedVector = GetPerp(hit.normal, velocity);
Vector2 newVector = magnitude * rotatedVector;
Debug.DrawLine(hit.point, hit.point + rotatedVector, Color.blue, float.MaxValue);
Debug.Log("normal: " + hit.normal + " rotated vector: " + rotatedVector + " velocity: " + velocity);
Debug.DrawLine(hit.point + hit.normal * 0.1f, hit.point + hit.normal * 0.1f + newVector, Color.red, float.MaxValue);
velocity = newVector;
ball.position = velocity + (hit.normal * radius + hit.point);
//simulate = false;
}
else
{
Debug.DrawLine(ball.position, ball.position + velocity.normalized * (velocity.magnitude + radius), Color.green, float.MaxValue);
ball.position += (velocity);
}
}
Vector2 GetPerp(Vector2 normal, Vector2 velocity)
{
Vector2 perp;
if (velocity.y <= 0)
{
normal.y *= -1;
}
else
{
normal.x *= -1;
}
perp.x = normal.y;
perp.y = normal.x;
return perp;
}
}