So let’s start by vertically pulling your code apart.
First, the Input.GetKeyDown() method is only valid in Update(). Docs tell you this but it’s a common oversight. Usually you check that click was pressed in Update() and set a boolean. Then in FixedUpdate() you check it, act on it ONCE, and clear the boolean.
Next remember that the mouse comes in Screen coordinates, the transform is in world coordinates, so comparing them isn’t going to be straightforward like you do there.
The Camera has methods to go back and forth between the two coordinate spaces.
One thing I cannot see from the video is what the controls are doing. Are they single taps causing the bird to climb like the Joust arcade game? Or do you hold it and he flaps as long as you are holding it?
Thanks a lot. I edited the code in the main post. I’ve adjusted as you said and the movement is a lot better. However, it still far from the DK parrot. But it’s my fault. I’ll try the WASD inputs to make it closer to DK.
If I remember, DK works like the Joust example.
You’re right again. I’m getting troubles with the camera.
Here’s a jousty-joust I just put together. Slap a cube in front of the camera, REMOVE the Box Collider from the cube (this uses Rigidbody2D) and run.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// @kurtdekker
// joust flapping ostrich controls
// drop me on a blank cube in front of the camera
// use left / right, FLAP to flap
// gravity might be pretty gnarly; pull the camera back...
[RequireComponent( typeof( Rigidbody2D))]
public class Joust : MonoBehaviour
{
// how far left/right of UP can you thrust?
const float MaxThrustVectorTilt = 30.0f;
// the larger this is, the more effective each flap is
const float MasterForceScale = 30.0f;
Rigidbody2D rb;
void Start ()
{
Physics2D.gravity = Vector2.down * 3.0f; // LESS GRAVITY!
rb = GetComponent<Rigidbody2D>();
}
bool flap;
void Update ()
{
// read flap intent
if (Input.GetKeyDown( KeyCode.Space) ||
Input.GetKeyDown( KeyCode.UpArrow) ||
false)
{
flap = true;
}
}
void FixedUpdate()
{
// forces only happen during a flap
if (flap)
{
flap = false; // consume
// raw input
float xInput = Input.GetAxisRaw("Horizontal");
// TODO: gather other left / right inputs?
// clamp
xInput = Mathf.Clamp( xInput, -1.0f, 1.0f);
// tilt
float angle = xInput * MaxThrustVectorTilt;
// rotation
Quaternion rotation = Quaternion.Euler ( 0, 0, -angle);
// rotate vector
Vector2 force = rotation * Vector2.up;
// scale for gravity
force *= Physics2D.gravity.magnitude;
// scale for mass
force *= rb.mass;
// scale for scale !
force *= MasterForceScale;
// use the force luke!!
rb.AddForce( force);
}
}
}