myRigidbody.MovePosition influences the force.
Hello,
somehow this part of my Code:
myRigidbody.MovePosition(targetPosition);
influences this one:
if (Input.GetMouseButtonDown(0))
{
myRigidbody.velocity = Vector2.zero;
myRigidbody.AddForce(new Vector2(0, upforce));
}
in that way that the added force isnt as big it was without the moveposition code. Can someone help me?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : $$anonymous$$onoBehaviour
{
public Rigidbody2D myRigidbody;
public Camera cam;
private float maxWidth;
private bool isGrounded;
private float upforce = 200f;
void Start()
{
//Screen.sleepTimeout = SleepTimeout.NeverSleep;
myRigidbody = GetComponent<Rigidbody2D>();
if (cam == null)
{
cam = Camera.main;
}
Vector2 upperCorner = new Vector2(Screen.width, Screen.height);
Vector2 targetWidth = cam.ScreenToWorldPoint(upperCorner);
float ballWidth = GetComponent<Renderer>().bounds.extents.x;
maxWidth = targetWidth.x - ballWidth;
}
// Update is called once per frame
void FixedUpdate()
{
Vector2 rawPosition = cam.ScreenToWorldPoint(Input.mousePosition);
Vector2 targetPosition = new Vector2(rawPosition.x, transform.position.y);
float targetWidth = $$anonymous$$athf.Clamp(targetPosition.x, -maxWidth, maxWidth);
targetPosition = new Vector2(targetWidth, targetPosition.y);
myRigidbody.$$anonymous$$ovePosition(targetPosition);
if (Input.Get$$anonymous$$ouseButtonDown(0))
{
myRigidbody.velocity = Vector2.zero;
myRigidbody.AddForce(new Vector2(0, upforce));
}
//myRigidbody.AddForce(Vector2.down * 100);
}
Thats my whole code yet. With the line of code to move the object so:
myRigidbody.$$anonymous$$ovePosition(targetPosition);
somehow the object doesnt get the force correctly applied to it.
ok, doing a move on two axis while trying to apply forces on one or two of the same axis just cannot work. You need to decide if it's a complete axis you want to ignore (like the y axis cause it should be influenced by forces), or if you just calculate everything together and set that as the rigidbodies velocity.
A sidenote to that. Setting velocity is the savest you can do. I tried with $$anonymous$$ovePosition once and it's just not a good way to move a rigidbody. While $$anonymous$$ovePosition complies with the interpolation settings set, it doesn't comply with collision (tried it once, just glitched through a wall).
Bottom line. I would calculate the velocity on the x axis for the mouseposition and leave y as is. Or do some fancy calculation with y so it's half the mouse click and half the force.
mouse position $$anonymous$$us position (both in world space), normalize times speed. that's the velocity in unit per second towards the target (overshooting).