我是联合/c#的新手,我想做一场乒乓球比赛。我在youtube上看了一篇教程。没有“错误”,除非球在接触球员后不会移动。
这是球号
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallCode : MonoBehaviour
{
private Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Vector2 position = transform.position;
position.x = position.x - 5.8f * Time.deltaTime;
transform.position = position;
}
}这是弹跳码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BallBounce : MonoBehaviour
{
private Rigidbody2D rb;
Vector3 lastVelocity;
// Start is called before the first frame update
void Awake()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
lastVelocity = rb.velocity;
}
private void OnCollisionEnter2D(Collision2D coll)
{
var speed = lastVelocity.magnitude;
var direction = Vector3.Reflect(lastVelocity.normalized, coll.contacts[0].normal);
}
}这是玩家代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float moveSpeed = 4.5f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float vertical = Input.GetAxis("Vertical");
Vector2 position = transform.position;
position.y = position.y + moveSpeed * vertical * Time.deltaTime;
transform.position = position;
}
}当我玩游戏时,球会与球员相撞,但不会弹跳。
发布于 2022-06-17 18:01:27
除了设置快速丢弃的局部变量外,OnCollisionEnter2D方法不会执行任何操作。您需要为BallCode或BallBounce类创建速度和方向变量,然后在确定更新()中的动作时设置BallCode类以使用这些变量。
发布于 2022-06-20 06:30:57
你可以尝试加入一个二维刚体属性到球体和消除重力。

添加一个C#脚本来控制球的运动,并在球上添加一个2D对撞机。
//Initial velocity
public float speed = 100f;
void Start()
{
this.GetComponent<Rigidbody2D>().AddForce
(Vector2.right * speed);
}添加一个2D对撞机:

在球体上加入一个二维的物理材料,这样球就可以弹跳了。

修改2D物理材料特性。
添加到球体的材料中。

添加播放器(正方形)和控制播放器的移动脚本。
void Update()
{
// The mouse moves with the player
float y = Camer.main.ScreenToWorldPoint
(Input.mousePosition).y
this.transform.position = new Vector3
(transform.position.x,y,0);
}在屏幕周围加上墙壁和脚本墙,以控制当球与墙相撞时垂直速度和球的方向的随机性。
public class Wall : MonoBehaviour
{
//Initial velocity
public float speed = 100f;
// Triggered when the collision ends
private void OnCollisionExit(Collision2D collision)
{
int r = 1;
if(Random.Range(0, 2) != -1)
{
r *= -1;
}
//add a vertical force
collision.gameObject.GetComponent<Rigidbody2D>().
AddForce(Vector2.up.*speed*r);
}
}达到以下效果:

https://stackoverflow.com/questions/72662507
复制相似问题