How to change the input direction of the virtual joystick according to the rotation of the camera so that the player advances? - rotation

I have a field with a josytick it worked fine and everything but when I turn the camera the player doesn't move in the right direction, I want him to move in the right direction but he moves in the opposite direction. Here is my code if you can help me? please.
public float speed;
public float rotationSpeed;
private CharacterController characterController;
public FixedJoystick moveJoystick;
private Animator _animator;
void Start()
{
characterController = GetComponent<CharacterController>();
_animator = GetComponent<Animator>();
}
void Update()
{
float horizontalInput = moveJoystick.Horizontal;
float verticalInput = moveJoystick.Vertical;
Vector3 movementDirection = new Vector3(horizontalInput, 0, verticalInput);
float magnitude = Mathf.Clamp01(movementDirection.magnitude) * speed;
movementDirection.Normalize();
transform.Translate(movementDirection * magnitude * Time.deltaTime, Space.World);
Vector3 velocity = movementDirection * magnitude;
characterController.Move(velocity * Time.deltaTime);
if (movementDirection != Vector3.zero)
{
_animator.SetBool("caminar", true);
Quaternion toRotation = Quaternion.LookRotation(movementDirection, Vector3.up);
transform.rotation = Quaternion.RotateTowards(transform.rotation, toRotation,
rotationSpeed * Time.deltaTime);
}
else
{
_animator.SetBool("caminar",false);
}
}

Related

Unity Camera vertically scrolling effect

I want to create a camera movement like idle miner tycoon. So the Camera should scroll vertically by panning with a typically scroll effect.
This is my code:
Vector3 touchStart;
public int upperLimit = 0;
public int lowerLimit = 7000;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
touchStart = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
if (Input.GetMouseButton(0))
{
Vector3 direction = touchStart - Camera.main.ScreenToWorldPoint(Input.mousePosition);
float finalYPos = Camera.main.transform.position.y + direction.y;
finalYPos = Mathf.Clamp(finalYPos, lowerLimit, upperLimit);
Camera.main.transform.position = new Vector3(Camera.main.transform.position.x, finalYPos, Camera.main.transform.position.z);
Debug.Log(finalYPos);
}
}
But how can I make that the scrolling is ran out. Actually the movement is stopping directly when I leave the mouse/thump.
Thank you for your help
Best regards
I found a Solution for everybody with the same problem:
[SerializeField]
private Camera cam;
Vector3 touchStart;
private float topLimit = 0f;
private float bottomLimit = -2000.0f;
private Vector3 _curPosition;
private Vector3 _velocity;
private bool _underInertia;
private float _time = 0.0f;
public float SmoothTime = 2;
public Vector3 direction;
void Update()
{
PanCamera();
if (_underInertia && _time <= SmoothTime)
{
cam.transform.position += _velocity;
float newY = Mathf.Clamp(cam.transform.position.y, bottomLimit, topLimit);
cam.transform.position = new Vector3(cam.transform.position.x, newY, cam.transform.position.z);
_velocity = Vector3.Lerp(_velocity, Vector3.zero, _time);
_time += Time.smoothDeltaTime;
}
else
{
_underInertia = false;
_time = 0.0f;
}
}
private void PanCamera()
{
if (Input.GetMouseButtonDown(0))
{
touchStart = cam.ScreenToWorldPoint(Input.mousePosition);
_underInertia = false;
}
if (Input.GetMouseButton(0))
{
Vector3 _prevPosition = _curPosition;
direction = touchStart - cam.ScreenToWorldPoint(Input.mousePosition);
float finalYPos = cam.transform.position.y + direction.y;
Debug.Log("Old: " + finalYPos);
finalYPos = Mathf.Clamp(finalYPos, bottomLimit, topLimit);
Debug.Log("New: " + finalYPos);
Vector3 desiredPosition = new Vector3(cam.transform.position.x, finalYPos, cam.transform.position.z);
cam.transform.position = desiredPosition;
_curPosition = desiredPosition;
_velocity = _curPosition - _prevPosition;
}
if (Input.GetMouseButtonUp(0))
{
_underInertia = true;
}
}

Unity Character ControllerTrying to accomplish smooth movement and jumping

When the player hits the ground the camera shakes and when he jumps he just get's teleported up in an unsmooth manner
public class PlayerController : MonoBehaviour {
CharacterController controller;
Vector3 motion = Vector3.zero;
#region Movement Variables
public float walkingSpeed = 4f;
public float runningSpeed = 6f;
public float jumpSpeed = 5f;
public float gravity = 9.8f;
#endregion Movement Variables
void Start () {
controller = GetComponent<CharacterController>();
}
void Update () {
motion = Vector3.zero;
motion.x = Input.GetAxis("Horizontal");
if (controller.isGrounded && Input.GetAxis("Vertical")>0) motion.y += jumpSpeed;
if (Input.GetKey(KeyCode.LeftShift))
{
motion.x *= runningSpeed;
}
else
{
motion.x *= walkingSpeed;
}
motion.y -= gravity;
}
void FixedUpdate()
{
controller.Move(motion * Time.deltaTime);
}
}
I'm trying to create smooth movement and currently it is not reliable at all. thanks for any helpers
Take controller.Move(motion * Time.deltaTime); out of FixedUpdate and put it at the very end of Update method.
In case you have some script on camera as well, for example, some implementation of a follow camera where you're working with the transform component of that camera in the Update loop, that should go in LateUpdate instead.
See this https://learn.unity.com/tutorial/update-and-fixedupdate#5c8a4242edbc2a001f47cd63
and https://docs.unity3d.com/ScriptReference/MonoBehaviour.LateUpdate.html
This implementation of a player controller for GameObject that has a Character Controller component may also help you.
void Update()
{
if (isDead) return;
isWalking = Input.GetButton("Walk");
isGrounded = characterController.isGrounded;
if (isGrounded)
{
// Move
float verticalAxis = Input.GetAxis("Vertical");
moveDirection = new Vector3(0, 0, verticalAxis);
moveDirection = transform.TransformDirection(moveDirection);
if (verticalAxis > 0 && isWalking)
{
moveDirection *= walkingSpeed;
}
else if (verticalAxis > 0)
{
moveDirection *= runningSpeed;
}
// Jump
if (Input.GetButtonDown("Jump"))
{
moveDirection.y = jumpSpeed;
//moveDirection.z = jumpDistance; in case some forward boost is required
moveDirection = transform.TransformDirection(moveDirection);
}
}
// Gravity
moveDirection.y -= gravity * Time.deltaTime;
characterController.Move(moveDirection * Time.deltaTime);
// Rotation
float horizontalAxis = Input.GetAxis("Horizontal");
transform.Rotate(0, horizontalAxis, 0);
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.FromToRotation(transform.up, GetHitNormal()) * transform.rotation, yRotationSpeed * Time.deltaTime);
}
// To keep local up aligned with global up on a slope ground
private Vector3 GetHitNormal()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, Vector3.down, out hit))
return hit.normal;
else
return Vector3.zero;
}

how do i properly start a javafx animation using timeline?

I am trying to use code gathered off of this website to make an application that bounces circles around. when i click now - it creates a circle that just seems to vibrate in place and does not bounce off of the borders.
HERE IS THE CODE HAT SOLLVED MY ISSUE THANKS GUYS
#FXML
private AnchorPane anchorPane;
#FXML
private Label ballCountLabel;
public int ballCount = 0;
public int mouseClick = 0;
Circle[] balls = new Circle[1000];
#Override
public void initialize(URL url, ResourceBundle rb) {
pane.setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
AnchorPane.setTopAnchor(pane, 0.0);
AnchorPane.setLeftAnchor(pane, 0.0);
AnchorPane.setTopAnchor(pane, 0.0);
AnchorPane.setRightAnchor(pane, 0.0);
}
#FXML
private void mouseAddBall(MouseEvent event) throws Exception {
balls[mouseClick] = new Circle(15, Color.BLANCHEDALMOND);
balls[mouseClick].relocate(event.getSceneX(), event.getSceneY());
pane.getChildren().add(balls[mouseClick]);
ballCount++;
ballCountLabel.setText("Ball Count: " + ballCount);
addBallMovement(balls[mouseClick]);
mouseClick++;
}
public void addBallMovement(Circle b){
final Timeline loop = new Timeline(new KeyFrame(Duration.millis(10), new EventHandler<ActionEvent>() {
double deltaX = 3;
double deltaY = 3;
#Override
public void handle(ActionEvent t) {
b.setLayoutX(b.getLayoutX() + deltaX);
b.setLayoutY(b.getLayoutY() + deltaY);
final Bounds bounds = pane.getBoundsInParent();
final boolean atRightBorder = b.getLayoutX() >= (bounds.getMaxX() - b.getRadius());
final boolean atLeftBorder = b.getLayoutX() <= (bounds.getMinX() + b.getRadius());
final boolean atBottomBorder = b.getLayoutY() >= (bounds.getMaxY() - b.getRadius());
final boolean atTopBorder = b.getLayoutY() <= (bounds.getMinY() + b.getRadius());
if (atRightBorder || atLeftBorder) {
deltaX *= -1;
}
if (atBottomBorder || atTopBorder) {
deltaY *= -1;
}
}
}));
loop.setCycleCount(Timeline.INDEFINITE);
loop.play();
I changed Ball to Circle to test your code. You are changing to the next ball in the balls array before you add movement to the current ball. This is probably giving you a NullPointerException.
Change
balls[mouseClick] = new Circle(event.getSceneX(), event.getSceneY(),
Math.random() * 20);
pane.getChildren().add(balls[mouseClick]);
mouseClick++;
ballCount++;
ballCountLabel.setText("Ball Count: " + ballCount);
addBallMovement(balls[mouseClick]); //<--You want to move the current ball. This code needs to be before mouseClick++
To:
balls[mouseClick] = new Circle(event.getSceneX(), event.getSceneY(),
Math.random() * 20);
pane.getChildren().add(balls[mouseClick]);
addBallMovement(balls[mouseClick]);
mouseClick++;
ballCount++;
ballCountLabel.setText("Ball Count: " + ballCount);

Health Bar in XNA

I have a little trouble with my health. When I was moving my personage, the healthbar lasped out of screen.
How can I keep it standing in my screen,something likes not moving anywhere. But when I move my personage, it'll move, too.
Here my code:
private Texture2D container, lifebar;
public Vector2 position;
public int fullHealth;
public int currentHealth;
public Healthbar(ContentManager content)
{
LoadContent(content);
fullHealth = lifebar.Width;
currentHealth = fullHealth;
}
private void LoadContent(ContentManager content)
{
container = content.Load<Texture2D>("Untitled");
lifebar = content.Load<Texture2D>("Health 2");
}
public void Update()
{
if (Keyboard.GetState().IsKeyDown(Keys.Right))
position.X += 3;
if (Keyboard.GetState().IsKeyDown(Keys.Left))
position.X -= 3;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(container, position ,Color.Red);
spriteBatch.Draw(lifebar, position, new Rectangle((int)position.X, (int)position.Y, currentHealth, lifebar.Height), Color.Pink);
}
You need to check the position.x and position.y values with the screen bounds otherwise you will always lose the health bar. You want something like:
if (position.X <= 10)
position.X = 10;
if (position.X >= 1270)
position.X = 1270;
etc.

Stop Skeleton Flickering in Kinect for Windows

Currently working on a project to find the X,Y position of the using who is standing in front of the kinect.
Even though the user is standing still the X,Y keep changing because the kinect skeleton is flickering. Could someone help me how to figure out a way to stop the skeleton flickering
Have you set the smoothing parameter? The following settings result in very smooth movements, but with a lot of latency.
TransformSmoothParameters smoothingParam = new TransformSmoothParameters
{
Smoothing = 0.7f;
Correction = 0.3f;
Prediction = 1.0f;
JitterRadius = 1.0f;
MaxDeviationRadius = 1.0f;
};
sensor.SkeletonStream.Enable(smoothingParam);
If that is not working good enough for you, I had developed a helper class for one of my kinect projects to smooth the coordinates of joints. You have to create an instance of the following helper class for each smoothed joint and call GetSmoothedXPosition/GetSmoothedYPosition with the screen coordinates of the joint:
internal class JointSmoothing
{
#region Constants and Enumerations
private const int QueueLength = 7;
private const double BaseValue = 0.9;
#endregion
#region Fields
private readonly Queue<double> myXValues = new Queue<double>(QueueLength);
private readonly Queue<double> myYValues = new Queue<double>(QueueLength);
#endregion
#region Public Methods
public double GetSmoothedXPosition(double x)
{
if (myXValues.Count >= QueueLength)
{
myXValues.Dequeue();
}
myXValues.Enqueue(x);
return ExponentialMovingAverage(myXValues);
}
public double GetSmoothedYPosition(double y)
{
if (myYValues.Count >= QueueLength)
{
myYValues.Dequeue();
}
myYValues.Enqueue(y);
return ExponentialMovingAverage(myYValues);
}
public void Clear()
{
myXValues.Clear();
myYValues.Clear();
}
#endregion
#region Private Implementation
private static double ExponentialMovingAverage(Queue<double> values)
{
double numerator = 0;
double denominator = 0;
int valueCount = values.Count;
int weight = valueCount - 1;
foreach (double value in values)
{
numerator += value * Math.Pow(BaseValue, weight);
denominator += Math.Pow(BaseValue, weight);
weight--;
}
double average = values.Sum();
average /= values.Count;
numerator += average * Math.Pow(BaseValue, valueCount);
denominator += Math.Pow(BaseValue, valueCount);
return numerator / denominator;
}
#endregion
}

Resources