Game Development Asked by Renan Valentin Ferreira on November 2, 2021
i’m creating a pong game for learning purpose and decided to have the Paddle moving freely but with a slight change in its control.
When pressing LEFT OR RIGHT it should move in polar coordinates facing the ball. And UP OR DOWN moves the paddle towards or backwards the ball.
I’ve spent the whole day trying out a few solutions but didn’t make it.
var ball = Vector3.zero; // target
var d = ball - translation.Value.ToVector3();
var radius = d.magnitude;
var dir = d.normalized * data.speed * deltaTime;
var angle = Vector3.Angle(ball, translation.Value);
var nextPos = translation.Value;
if (data.input.x > 0)
{
nextPos.x += dir.x + 15 * math.sin(angle) * data.speed * deltaTime;
nextPos.z += dir.z + 15 * math.cos(angle) * data.speed * deltaTime;
}
if (data.input.x < 0)
{
nextPos.x -= dir.x + 15 * math.sin(angle) * data.speed * deltaTime;
nextPos.z -= dir.z + 15 * math.cos(angle) * data.speed * deltaTime;
}
translation.Value = nextPos;
Sorry for my initial shallow answer. After doing research, I could not find where I had found the initial Mathf.PI solution. But after fiddling around in Unity, I came up with my own solution to this problem. Here is the code below
{
public Transform ball;
public float speed = 1.0f;
private float leftToRightMovement;
/*
private Vector3 paddlePosition;
private float distanceFromBall;
private float offsetMultiplier;
*/
void Update()
{
//This is my attempt to control the speed of the paddle relative to the distance to the ball, but the speed kept multiplying into infinity.
/*
Vector3 offset = ball.position + transform.position;
float sqrLen = offset.sqrMagnitude;
Debug.Log("distance from ball is " + sqrLen);
offsetMultiplier = sqrLen;
speed = speed + offsetMultiplier;
*/
float forwardBackward = Input.GetAxis("Vertical") * speed * Time.deltaTime;
float leftToRight = Input.GetAxis("Horizontal") * speed * Time.deltaTime;
transform.Translate(0.0f, 0.0f, forwardBackward);
transform.Translate(leftToRight, 0.0f, 0.0f);
transform.LookAt(ball);
}
The main idea here is to assign the ball as a game object and using "LookAt" to rotate your paddle toward the ball. From there, you can use the z position of the paddle to move closer and further away, and the x position to move side to side. Since the z position is always looking at the ball, the x movement will always be in a circle around the ball.
The one problem I had was when the paddle got very far away, the speed was relatively much slower than close up. I couldn't come up with a solution to that problem, but also not sure if you need that. My attempt is commented in the code snippet.
Goodluck and cheers!
Answered by defunct_artist on November 2, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP