So I've got a little sledding prototype going. I'm currently coding some controls to compliment the RigidBody physics I've applied. My goal is to apply a force in the opposite direction of the turn left or right in order to get a sort of skidding, edge catching effect, and then apply a force forward to compensate for the loss of momentum.
However I can't get that far, because for whatever ever reason I can't get the GetKeyDown() or GetKeyUp() functions to work. I've included the code below. Basically what happens is the "Button released." text gets output constantly, and then once in a while I will get a "Button pressed" output that happens only once before reverting back to the "Button released." outputs. Even this is rare. Usually I get no indication of any detection.
I'm sure I'm missing something miniscule, and I have looked for similar questions, but none of them seem to solve my problem. If anyone can give me any ideas I'd be very grateful. Also, any optimization tips would be appreciated. I'm still a little new to C# and Unity.
I'm in the middle of tweaking and experimenting so I apologize if I missed some un-necessary comments.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
private Rigidbody rb;
public bool sidePhysics;
public bool keyPress;
// Use this for initialization
void Awake()
{
rb = GetComponent<Rigidbody>();
}
// Update is called once per frame
void FixedUpdate()
{
var x = Input.GetAxis("Horizontal") * Time.deltaTime * 50.0f;
// No vertical controlls for now.
//var z = Input.GetAxis("Vertical") * Time.deltaTime * 40.0f;
// Get axis against which to apply force
var turnAngle = rb.transform.position.x;
transform.Rotate(0, x, 0);
//transform.Translate(0, 0, z);
// Debug to test input detection
keyPress = Input.GetKeyDown(KeyCode.A);
Debug.Log("keyPress: " + keyPress);
// On either right or left key input down, apply force
// Later once keys are being detected - addForce forward too
if (Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.LeftArrow)
|| Input.GetKeyDown(KeyCode.A) || Input.GetKeyDown(KeyCode.D))
{
Debug.Log("Button pressed. ");
// Add opposing force proportionate to the degree of the turn
rb.AddForce((turnAngle * (-x * 10)), 0, 0, ForceMode.Acceleration);
}
else
{
Debug.Log("Button released.");
}
//Debug.Log("RigidBody: " + rb +
// " Rotation: " + x +
// " turnAngle: " + turnAngle);
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…